Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

π 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading