简体   繁体   中英

Trignometry in C# Cos & CosA

I am running into something that should be very simple to answer but i can't put my fingers on it. It has been quite sometime since i have done some trigonometry.

double cosValue = -2.7105054312E-20;
// (ACos) returns the angle
var deducedAngleInRadian = System.Math.Acos(cosValue);
var cos = System.Math.Cos(deducedAngleInRadian);

Console.WriteLine(cosValue);
Console.WriteLine(deducedAngleInRadian);
Console.WriteLine(cos);

Output:

-2.7105054312E-20
1.5707963267949
6.12303176911189E-17

How come that cosValue and cos are not the same?

Did you notice how much the two values are close of 0, and close to each other ?

The floating point (im)precision and the implementation of each methods may probably perfectly explain that. Those methods are not perfect, for example they are relying on an approximation of Pi (of course, as Pi can't be stored in a computer ;)).

You could probably achieve a better precision (do you really need it) with a scientifical library, dedicated to this and using higher precision types than Double. You could may be find some interesting stuff in Math operations using System.Decimal in C#? or https://stackoverflow.com/questions/1387430/recommended-math-library-for-c-net

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM