ratty
ratty

Reputation: 13434

double conversion value error in c#

double deg=90;
double two= 2* System.Math.PI;
double rad=(two)*(deg/360);

the original value when calculating manually ,rad is 1.5707963267948966 but rad shows when debugging is 1.5707963705062866 what is reason for this and how do i fix it.but correct answer is manual calculation answer only......

Here are the numbers for easier comparison:

1.5707963267948966
1.5707963705062866
         --------- <-- differences

during the debug i put the pointer in right side that means calculation side it shows correct answer but the error happen when storing that value to rad.

is anybody help for me.i need it.

Upvotes: 3

Views: 671

Answers (6)

Richard Morgan
Richard Morgan

Reputation: 7681

Here's a pretty good description of floating-point arithmetic:

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391276

Using your code I can't reproduce what you're seeing.

I did this:

using System;

namespace ConsoleApplication18
{
    class Program
    {
        static void Main(string[] args)
        {
            double deg = 90;
            double two = 2 * System.Math.PI;
            double rad = (two) * (deg / 360); 

            Console.Out.WriteLine(rad);
        }
    }
}

And I got this output:

1.5707963267949

When hovering over the rad variable when on a breakpoint on the WriteLine line, I saw the following value in the tooltip

1.5707963267948966

Where/how did you see that other value?

The difference above is probably due to me not specifying the precision in my write-call, so perhaps I could get all the digits there as well. I'm certainly not seeing the second value you mention.

Upvotes: 0

Joel Etherton
Joel Etherton

Reputation: 37523

Double, float and decimal are really your only standard options. If they are not precise enough for your needs, you will need to create your own type and provide it a means of storing these high precision values and its own operators for performing mathematical functions.

You'll notice the double type is accurate to 7 places, the decimal type will be accurate for slightly more. If you want greater precision than that, you will need to come up with an algorithm for computing it and storing it.

Upvotes: 0

Shimrod
Shimrod

Reputation: 3205

You should use a decimal value, which is more accurate than double.

Upvotes: 0

Ian
Ian

Reputation: 34489

Use a decimal type rather than double. It's due to floating point precision.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062502

Rounding errors happen; it isn't infinite precision. You will have to test whether values are suitably close - don't just test for equality. In some cases you might also see subtle differences by applying the operators in a different sequence, so you don't swamp small numbers with magnitude.

Upvotes: 8

Related Questions