How to find the slope: output format ((A,slope), B) - python-3.x

I'm enrolled in a Data Science course, and I'm trying to solve some programming problems, I haven't worked with Python in a long time, but I'm trying to improve my knowledge of the language.
Here is my problem:
def find_slope(x1, y1, x2, y2):
if (x1) == (x2):
return "inf"
else:
return ((float)(y2-y1)/(x2-x1))
Here is my driver code:
x1 = 1
y1 = 2
x2 = -7
y2 = -2
print(find_slope(x1, y1, x2, y2))
This is my output:
0.5
I'm not sure how to get it in the correct format, such as (((1, 2), .5), (3, 4))
NOTE: I wrote the code for the driver.

You can do this:
def find_slope(input):
x1 = input[0][0]
y1 = input[0][1]
x2 = input[1][0]
y2 = input[1][1]
if (x1) == (x2):
slope = "inf"
else:
slope = ((float)(y2-y1)/(x2-x1))
output = (((x1, y1), slope), (x2, y2))
return output
I changed the input to match the input format given in the screenshot.
Now the input is a single tuple, containing two tuples. Each of the inner tuples contain a x coordinate and a y coordinate.
You can call the function using
input = ((1, 2), (-7, -2))
output = find_slope(input)
The output will be in the format ((A, slope), B), where A and B are tuples containing the x and y coords.

Related

Nott getting same result when trying to get slope from 2 points

I'm trying to make something that would give me the slope and y-intercept from 2 points. Sometimes it would give me the correct values, but other times it would give me something close to correct but wrong.
Anyone know any thing that I could have done wrong? (Also, I feel like I should say that I'm just now starting to learn python)
y2 = input('Y2: ')
y1 = input('Y1: ')
x2 = input('X2: ')
x1 = input('X1: ')
y2 = float(y2)
y1 = float(y1)
x2 = float(x2)
x1 = float(x1)
over = y2-y1
under = x2-x1
m = over/under
y = float(y2)
x = float(x2)
m = float(m)
ym = y-m
b = ym/x
print(f'Y = {m}x + {b}')
it appears as though the mathematics for the intercept b is incorrect.
it would be logical to use the x1, y1 coordinate with the slope to generate b.
assume that you want to find x0, y0 where y0 = b. Then you would do a similar calculation (already having calculated m before as you correctly did).
So (y1-b) / x1 = m. and you can just rearrange this to get:
b = y1 - m*x1.
So this works:
x1, y1 = 1, 1
x2, y2 = 2, 2
over = y2-y1
under = x2-x1
m = over/under
b = y1 - m*x1
print(f'Y = {m}x + {b}')
returns this:
Y = 1.0x + 0.0

Issue with finding angle between 3 points in Python

I have 3 points p1(x1, y1), p2(x2, y2) and p3(x3, y3). I am trying to calculate angle (in anti-clockwise direction) between these 3 points. I am using following dot product method as provided in multiple blogs and SE sites (like this).
def angle_between(p1, p2, p3):
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
v21 = (x1 - x2, y1 - y2)
v23 = (x3 - x2, y3 - y2)
dot = v21[0] * v23[0] + v21[1] * v23[1]
det = v21[0] * v23[1] - v21[1] * v23[0]
theta = np.rad2deg(np.arctan2(det, dot))
print(theta)
It is giving me correct angle for any points which are not on the straight line. For example
p1 = (0, 0)
p2 = (1, 0)
p3 = (1, 1)
angle_between(p1, p2, p3) # Prints -90
angle_between(p3, p2, p1) # Prints +90
However, if points are on the straight line, it is giving me same answer
p1 = (0, 0)
p2 = (1, 0)
p3 = (2, 0)
angle_between(p1, p2, p3) # Prints +180
angle_between(p3, p2, p1) # Prints +180
Here I was expecting (p3, p2, p1) to give -180. What am I missing here? If the method I am using is not correct, can someone help me point towards the correct method?
I have tried to use direct cosine law (as given here) but it only provides me angle without any sense of direction of the angle.
Check out this solution. It always provides positive angles, measured in anti-clockwise direction:
from math import atan2, degrees
def angle_between(p1, p2, p3):
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
deg1 = (360 + degrees(atan2(x1 - x2, y1 - y2))) % 360
deg2 = (360 + degrees(atan2(x3 - x2, y3 - y2))) % 360
return deg2 - deg1 if deg1 <= deg2 else 360 - (deg1 - deg2)

How to calculate difference between rows in Pandas DataFrame?

In a dataframe I have 4 variables that are the X, Y, Z and W orientations of a robot. Each line represents a measurement with these four values.
x = [-0.75853, -0.75853, -0.75853, -0.75852]
y = [-0.63435, -0.63434, -0.63435, -0.63436]
z = [-0.10488, -0.10490, -0.10492, -0.10495]
w = [-0.10597, -0.10597, -0.10597, -0.10596]
df = pd.DataFrame([x, y, z, w], columns=['x', 'y', 'z', 'w'])
I wrote the function below that returns three differences between two quaternions:
from pyquaternion import Quaternion
def quaternion_distances(w1, x1, y1, z1, w2, x2, y2, z2):
""" Create two Quaternions objects and calculate 3 distances between them """
q1 = Quaternion(w1, x1, y1, z1)
q2 = Quaternion(w2, x2, y2, z2)
dist_by_signal = Quaternion.absolute_distance(q1, q2)
dist_geodesic = Quaternion.distance(q1, q2)
dist_sim_geodec = Quaternion.sym_distance(q1, q2)
return dist_by_signal, dist_geodesic, dist_sim_geodec
This difference is calculated based on the values of the second line by the values of the first line. Thus, I cannot use the Pandas apply function.
I have already added three columns to the dataframe, so that I receive each of the values returned by the function:
df['dist_by_signal'] = 0
df['dist_geodesic'] = 0
df['dist_sim_geodec'] = 0
The problem is: how to apply the above function to each row and include the result in these new columns? Can you give me a suggestion?
Consider shift to create adjacent columns, w2, x2, y2, z2, of next row values then run rowwise apply which does require axis='columns' (not index):
df[[col+'2' for col in list('wxyz')]] = df[['x', 'y', 'z', 'w']].shift(-1)
def quaternion_distances(row):
""" Create two Quaternions objects and calculate 3 distances between them """
q1 = Quaternion(row['w'], row['x'], row['y'], row['z'])
q2 = Quaternion(row['w2'], row['x2'], row['y2'], row['z2'])
row['dist_by_signal'] = Quaternion.absolute_distance(q1, q2)
row['dist_geodesic'] = Quaternion.distance(q1, q2)
row['dist_sim_geodec'] = Quaternion.sym_distance(q1, q2)
return row
df = df.apply(quaternion_distances, axis='columns')
print(df)
You can use.
Quaternions=df.apply(lambda x: Quaternion(x), axis=1)
df['dist_by_signal'] = 0
df['dist_geodesic'] = 0
df['dist_sim_geodec'] = 0
df.reset_index(drop=True)
for i in df.index:
q1=Quaternions[i]
if i+1<len(df.index):
q2=Quaternions[i+1]
df.loc[i,['dist_by_signal','dist_geodesic','dist_sim_geodec']]=[Quaternion.absolute_distance(q1, q2), Quaternion.distance(q1, q2),Quaternion.sym_distance(q1, q2)]
print(df)
x y z w dist_by_signal dist_geodesic \
0 -0.75853 -0.75853 -0.75853 -0.75852 0.248355 0.178778
1 -0.63435 -0.63434 -0.63435 -0.63436 1.058875 1.799474
2 -0.10488 -0.10490 -0.10492 -0.10495 0.002111 0.010010
3 -0.10597 -0.10597 -0.10597 -0.10596 0.000000 0.000000
dist_sim_geodec
0 0.178778
1 1.799474
2 0.010010
3 0.000000

Unable to get the simplified coordinates using sympy - python

I have x2, x3, y2, y3, d1, d2, d3 values which is,
x2 = 0
x3 = 100
y2 = 0
y3 = 0
d1 = 100
d2 = 100
d3 = 87
When I use the below script,
from sympy import symbols, Eq, solve
x, y = symbols('x y')
eq1 = Eq((x - x2) ** 2 + (y - y2) ** 2 - d2 ** 2)
eq2 = Eq((x - x3) ** 2 + (y - y3) ** 2 - d3 ** 2)
sol_dict = solve((eq1, eq2), (x, y))
I got the ans as,
sol_dict = [(12431/200, -87*sqrt(32431)/200), (12431/200, 87*sqrt(32431)/200)]
How can I achieve the simplified solution like
sol_dict = [(62.155, -78.33), (62.155, 78.33)]
in python?
You can numerically evaluate the solution to get floats:
In [40]: [[x.evalf(3) for x in s] for s in sol_dict]
Out[40]: [[62.2, -78.3], [62.2, 78.3]]
I would only recommend doing that for display though. If you want to use the values in sol_dict for further calculations it's best to keep them as exact rational numbers.

TypeError: a float is required in python 3

I have a Python3 script as follows:
import math
Value_1 = float(input("what's the X1 value?")), float(input("what's the X2 value?"))
Value_2 = float(input("what's the Y1 value?")), float(input("what's the Y2 value?"))
equation =(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))
print (equation)
with this output
what's the X1 value?3.0
what's the X2 value?12.0
what's the Y1 value?10.0
what's the Y2 value?110.0
Then the program return this error:
TypeError Traceback (most recent call last)
<ipython-input-15-cc8d8b28ff67> in <module>()
5
6
----> 7 equation = float(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))
8
9 print (equation)
TypeError: a float is required
I have tried to use all tips for other questions but error persist. Any tips?
no one cares about my question but I figure out it by myself. Here we go:
import math
x1 = float(input("what's the X1 value?"))
x2 = float (input("what's the X2 value?"))
print (x2 - x1)
xdiff = abs (x2 - x1)
print (xdiff)
y1 = float(input("what's the y1 value?"))
y2 = float (input("what's the y2 value?"))
ydiff = abs(y2 - y1)
print (ydiff)
math.sqrt(math.pow(xdiff,2) + math.pow(ydiff,2))
What is the problem?
By assigning to inputs to Value_1, separated by a comma, you are defining a tuple. As a short example for this:
In [1]: tup = 42, 23
In [2]: type(tup)
Out[2]: tuple
However, the math.sqrt function requires a float value as input, not a tuple.
How to solve this
You can use tuple unpacking to keep the structure of your original post intact:
import math
# read in x and y value of the first point and store them in a tuple
point_1 = float(input("What is the x value of point 1? ")), float(input("What is the y value of point 1? "))
# read in x and y value of the second point and store them in a tuple
point_2 = float(input("What is the x value of point 2? ")), float(input("What is the y value of point 2? "))
# This is where the tuple unpacking happens.
# After this you have the x and y values
# of the points in their respective variables.
p1_x, p1_y = point_1
p2_x, p2_y = point_2
# At this point you can use point_1 when you need both x and y value of
# of the first point. If you need only the x or y value you can use the
# unpacked coordinates saved in p1_x and p1_y respectively.
x_diff = abs(p1_x - p2_x)
y_diff = abs(p1_y - p2_y)
distance = math.sqrt(math.pow(x_diff, 2) + math.pow(y_diff, 2))
print("Distance of {} and {} is {}".format(point_1, point_2, distance))
As you can see above it can be helpful to save the information for the point as a tuple first and then use the unpacked coordinates at at a different point.
I hope this sheds some light on what happened.

Resources