Search code examples
vbamathatan2

VBA Atan2 function returns incorrect result


I was trying to solve a problem over on Math Stackexchange (https://math.stackexchange.com/questions/4752547/3d-transformation-matrix-to-euler-angles) and I found that my problem seems to be related to VBA's execution of the Atan2 function. Here's a minimum code example:

Python:

print(math.atan2(-0.384, 0.617) * 180 / math.pi)

Result:

-31.896741982732813

VBA:

Debug.Print Application.Atan2(-0.384, 0.617) * 180 / Pi

Result:

121.896741982725

I checked without the degrees conversion, and the results were similarly incorrect.

Any idea what's happening here?


Solution

  • These functions have different parameter order (y-x versus x-y).

    Phthon:
    math.atan2(y, x)
    
    VBA:
    expression.Atan2 (Arg1, Arg2)  ' Arg1 is The x-coordinate of the point.
    

    Please refers to Microsoft document:

    WorksheetFunction.Atan2 method (Excel)

    You will get the same answer with:

    Python:
    print(math.atan2(0.617, -0.384) * 180 / math.pi)