Math.Cos(0.5 * Math.PI) doesn't evaluate exactly to zero
In mathematics the cosine of 0.5Pi (in radians) is zero. In C# however the equivalent expression
Math.Cos(0.5 * Math.PI) would evaluate to 6.12303176911189E-17. A value that is very close to zero. I was wondering why it won't evaluate to exactly zero and if there is a way to correct this.
When you work with floating point numbers, then you will notice that everything you are doing is non-exact science. Often you don't notice, because on average, we don't show 15 digits behind the comma. But occasionally, we find ourselves wondering why zero isn't equal to zero...
To resolve this, there's only so much you can do, and in this case, the two things you can do is to use a Decimal, which has a higher precision then a double, or you can use rounding.
This is an age old problem that computers have to live with. Only real math packages (like gpari or ubasic, but also mathlabs), who do calculations in a totally different way, have a way out of this.
Another way to look at this: PI has infinitely many decimals, and so does every calculation that involves PI. A computer has only a limited amount of available memory. To keep things workable, the IEEE consortium has invented the IEEE floating points which uses a well-defined behavior for rounding and precision: http://en.wikipedia.org/wiki/IEEE_floating-point_standard
0
a_anis3000Author Commented:
I guess that is a limitation of floating point numbers that their precision is not perfect.
I tried using decimal unfortunately the Math.Cos method takes only double parameter so I tried rounding it as suggested and it worked for me.
> I guess that is a limitation of floating point numbers that their precision is not perfect.
see my earlier comment: it is mathematically and technically impossible to have perfect precision. And as long as resources are limited in the world, this will never change.
Before grading below A, it is a good idea to give an expert an opportunity to give you all you need to understand a solution. Please read the 10pts must principle of EE and help us, experts, to earn that.
0
Featured Post
In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.
To resolve this, there's only so much you can do, and in this case, the two things you can do is to use a Decimal, which has a higher precision then a double, or you can use rounding.
This is an age old problem that computers have to live with. Only real math packages (like gpari or ubasic, but also mathlabs), who do calculations in a totally different way, have a way out of this.
-- Abel --