Pregunta

I'm completely stumped dealing with something quite simple. The following lines are a part of a much much larger program. Thing and stuff are two objects on a grid, and I need to find the angle between them, in relation to the y-axis. math.atan takes in a floating point number, which I why I need to type cast the distance between the objects.

m_angle = math.degrees(math.atan(float(thing.position()[1]-stuff.position()[1]) / float(thing.position()[0]-stuff.position()[0])))

m_angle = math.degrees(math.atan(float(thing.position()[1]-stuff.position()[1]) / thing.position()[0]-stuff.position()[0]))

The .position calls all return integers.

I get different results while running my program, for each line. The first two should return exactly the same result, a float.

What I don't understand, is how I can possibly get different results depending on whether I run line 1 or line 2 :/

This is a part of a simulation,

¿Fue útil?

Solución

Difficult to answer at the rate you are editing but:

m_angle = math.degrees(math.atan(float(thing.position()[1]-stuff.position()[1]) / float(thing.position()[0]-stuff.position()[0])))

the bit inside the atan is equivalent to something/(a-b)

m_angle = math.degrees(math.atan(float(thing.position()[1]-stuff.position()[1]) / thing.position()[0]-stuff.position()[0]))

the bit inside the atan is equivalent to (something/a)-b

Otros consejos

To avoid all confusion, use

m_angle = math.atan2(thing.position()[1]-stuff.position()[1], thing.position()[0]-stuff.position()[0]);
m_angle = math.degrees(m_angle);

No division included, thus no integer-to-float conversion necessary.

This will give, in difference to the atan function, the correct angle if the angle is in the II. or III. quadrant. The atan function gives the result mod 180°, the atan2 function mod 360°. Depending on the application, the one or the other could be the intended result.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top