2

In Python, if one wanted to create the effect of atan2() from the atan() function, how would one go about this? For example, if I had cartesian coordinates (x, y) and wanted to find the arctan of (x, y) using the atan() function such that it worked in all quadrants, so regardless of the sign of x or y, how could I do this without using the atan2() function? In the example of converting between cartesian and polar:

def cartopol(x, y):
    r = (x**2 + y**2)**0.5
    p = math.atan(y/x)
    return(r,p)

This formula for returning the correct angle in radians would not currently work using the atan() function, so what must change?

martineau
  • 119,623
  • 25
  • 170
  • 301
DPJDPJ
  • 147
  • 2
  • 9
  • Why don't you just use `atan2`? It's bad practice to try and rewrite built-ins, re-enventing the wheel. – DjaouadNM Oct 21 '20 at 12:18
  • 1
    This [post](https://stackoverflow.com/questions/283406/what-is-the-difference-between-atan-and-atan2-in-c) explains a lot of the differences between `atan` and `atan2` – AnsFourtyTwo Oct 21 '20 at 12:20
  • 2
    If you know the signs of y and x, then you can manually add `pi` or `-pi` to `math.atan(y/x)` depending on the signs of `y` and `x` to get the right value. Obviously, this it not recommended since you already have a `math.atan2` function – rafaelc Oct 21 '20 at 12:25
  • 1
    Does this answer your question? [What is the difference between atan and atan2 in C++?](https://stackoverflow.com/questions/283406/what-is-the-difference-between-atan-and-atan2-in-c) – Peter O. Oct 21 '20 at 14:03
  • @rafaelc Can you explain this concept to me please? This is exactly what I need to know. Thanks. – DPJDPJ Oct 21 '20 at 14:04
  • @rafaelc: You should add your comments as an answer. – Peter O. Oct 21 '20 at 14:38
  • @MrGeek: I learned pretty much everything I know about C by rewriting functions from the standard library. Of course I wouldn't use these rewritten functions in production code. But I also wouldn't recommend skipping a good learning opportunity under the pretense that it's "bad practice". – Stef Oct 26 '20 at 17:05
  • @Stef I understand your point, I do this too, I just assumed the OP was making this for use in production code, other than that, I agree with you, I re-invent the wheel lots of times for fun, and it's pretty rewarding. – DjaouadNM Oct 26 '20 at 22:18

1 Answers1

2

In a nutshell, math.atan only works for quadrants 1 and 4. For quadrants 2 and 3 (i.e. for x < 0), then you'd have to add or subtract pi (180 degrees) to get to quadrants 1 and 4 and find the respective value for the theta. In code, it means that

if (y < 0 and x < 0): 
    print(math.atan(y/x) - math.pi)
elif (y > 0 and x < 0): 
    print(math.atan(y/x) + math.pi)

For more reference, take a look at atan2. The other two use cases are those in which x > 0, which works well with atan.

rafaelc
  • 57,686
  • 15
  • 58
  • 82