Search code examples
c++c++20trigonometrycmath

the cos function in cmath libray is not working correctry


i am using c++20 and cos() is not working correctly(visual studio)

#include <cmath>
#include <numbers>
//it is supposed to give me 0
std::cout << cos(std::numbers::pi / 2);
//it gives 6.12323e-17 instead

Solution

  • π and π/2 are irrational numbers. All finite numbers represented in a floating-point format are rational numbers. In fact, they are in a more restricted subset in which every number has the form ±Mbe, where M is an integer bounded by the format, b is the base used for the format, most often 2, sometimes 10, and e is an integer also bounded by the format.

    The format most commonly used for double is IEEE-754 binary64. In this format, 0 ≤ M < 253 and −1074 ≤ e ≤ 971.

    In this format, the representable value closest to π/2 is exactly 1.5707963267948965579989817342720925807952880859375 (with M = 3537118876014220, e = −51). That is what you should get for std::numbers::pi / 2; it is the best possible result in that format.

    The cosine of that number is approximately 6.12323•10−17.