abs() is a built-in function, so just replace all occurrences of math.abs with abs.
You should also use the isinstance() function for type checking instead of using type() and comparing, for example:
def distance_from_zero(num):
if isinstance(num, (int, float)):
return abs(num)
else:
return "Not an integer or float!"
Note that you may also want to include long and complex as valid numeric types.
Videos
abs() is a built-in function, so just replace all occurrences of math.abs with abs.
You should also use the isinstance() function for type checking instead of using type() and comparing, for example:
def distance_from_zero(num):
if isinstance(num, (int, float)):
return abs(num)
else:
return "Not an integer or float!"
Note that you may also want to include long and complex as valid numeric types.
As others pointed out, abs is builtin so it isn't imported from the math module.
I wanted to comment on your type checking. Another way that is the most "pythonic" is to use a try: except: block to check the type:
def distance_from_zero(num):
try:
return abs(num)
except ValueError:
return "Not an numeric type!"
This takes care of the issue that F.J. pointed out, that long and complex won't be considered. This example uses "duck typing" (if it walks like a duck and quacks like a duck, it must be a duck). If abs works, your function succeeds. If you supply something abs doesn't know how to handle a ValueError will be raised an it will return your error message.
In the formula, the numerator is the dot product of two vectors, and the denominator is the product of the norms of the two vectors.
Here is a simple way to write your formula:
import math
def dot_product(u, v):
(x1, y1) = u
(x2, y2) = v
return x1 * x2 + y1 * y2
def norm(u):
(x, y) = u
return math.sqrt(x * x + y * y)
def get_angle(u, v):
return math.acos( dot_product(u,v) / (norm(u) * norm(v)) )
def make_vector(p, q):
(x1, y1) = p
(x2, y2) = q
return (x2 - x1, y2 - y1)
#first direction vector
#punt 1, PQ
# [x,y]
P = (1,1)
Q = (5,3)
#punt 2, RS
R = (2,3)
S = (4,1)
angle = get_angle(make_vector(p,q), make_vector(r,s))
print(angle)
From what I see, the result of your code would always be pi or 0. It will be pi if one of the mu1 or mu2 is negative and when both are negative or positive it will be zero. If I remember vectors properly : Given two vectors P and Q, with say P = (x, y) and Q = (a, b) Then abs(P) = sqrt(x^2 + y^2) and P. Q = xa+yb. So that cos@ = P. Q/(abs(P) *abs(Q)). If am not clear you can give an example of what you intend to do