Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't c# calculate exact values of mathematical functions

Tags:

c#

rounding

Why can't c# do any exact operations.

Math.Pow(Math.Sqrt(2.0),2) == 2.0000000000000004

I know how doubles work, I know where the rounding error is from, I know that it's almost the correct value, and I know that you can't store infinite numbers in a finite double. But why isn't there a way that c# can calculate it exactly, while my calculator can do it.

Edit

It's not about my calculator, I was just giving an example:

http://www.wolframalpha.com/input/?i=Sqrt%282.000000000000000000000000000000000000000000000000000000000000000000000000000000001%29%5E2

Cheers

like image 263
Timo Willemsen Avatar asked Jan 05 '11 12:01

Timo Willemsen


2 Answers

Chances are your calculator can't do it exactly - but it's probably storing more information than it's displaying, so the error after squaring ends up outside the bounds of what's displayed. Either that, or its errors happen to cancel out in this case - but that's not the same as getting it exactly right in a deliberate way.

Another option is that the calculator is remembering the operations that resulted in the previous results, and applying algebra to cancel out the operations... that seems pretty unlikely though. .NET certainly won't try to do that - it will calculate the intermediate value (the root of two) and then square it.

If you think you can do any better, I suggest you try writing out the square root of two to (say) 50 decimal places, and then square it exactly. See whether you come out with exactly 2...

like image 160
Jon Skeet Avatar answered Nov 05 '22 20:11

Jon Skeet


Your calculator is not calculating it exactly, it just that the rounding error is so small that it's not displayed.

like image 2
Jackson Pope Avatar answered Nov 05 '22 20:11

Jackson Pope