Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[Solved] incorrect calculation in Qt Script



  • While when i calculete Math.sin(Math.PI) i get this answer: 1.2246467991473532e-16 instead of 0
    Same with Math.cos(Math.PI/2) = 6.123233995736766e-17
    Why is this happening?
    I advance thank you for your help!



  • THis is not a Qt Script problem, but a computer problem. There is a limit to the precision of numbers you can express in floating point numbers. That is what you are seeing. You should compare them using an epsilon.



  • Limited numerical precision of the floating point representation of numbers is the problem.



  • As i understude, you dont understunde me(maybe i am dont right, my english is bad) i say not about
    e-16 in 1.2246467991473532e-16, i say about sin(pi) should be equal 0 as cos(pi/2)



  • As far as I understand the problem is that Math.PI does not express the pure PI, since Math.PI is limited by the precision of the computer floating numbers. I guess you will have the same result (or a similar one) using another math library.


  • Moderators

    [quote author="Ruzik" date="1317636902"]As i understude, you dont understunde me(maybe i am dont right, my english is bad) i say not about
    e-16 in 1.2246467991473532e-16, i say about sin(pi) should be equal 0 as cos(pi/2)[/quote]

    I'm afraid they are right, mate. With floating point, you cannot really get exactly 0, save for a few cases.



  • [quote author="Ruzik" date="1317636902"]As i understude, you dont understunde me(maybe i am dont right, my english is bad) i say not about
    e-16 in 1.2246467991473532e-16, i say about sin(pi) should be equal 0 as cos(pi/2)[/quote]

    Well, 6.123233995736766e-17 ≈ 0, as far as floating point numbers are concerned.



  • Clear, thank you for your help!



  • Also, the trigonometric functions are transcendental functions and so cannot be calculated exactly. All implementations use approximations that are good to some degree of accuracy for a range of inputs.

    As Andre suggested, test it with an epsilon (small value) to see if it is in agreement with your criteria. i.e.

    @
    const double eps = 1.0e-10; // as an arbitrary example
    double value = sin( pi ); // pi defined somewhere else
    const double test = 0.0;
    if ( qAbs( value - test ) < eps )
    qDebug() << "Values agree within some small value epsilon";
    @

    Obviously you can use different values for eps and test as needed in your particular cases. This is just a fact of life when working with floating point representations on machines with limited memory.


Log in to reply