5

Consider this code:

double result = Math.Sqrt(4746073226998689451);

For result I get 2178548422 instead of 2178548421.999999854etc... How can I get more precise result?

sventevit
  • 4,766
  • 10
  • 57
  • 89

4 Answers4

7

There is a bunch of high precision maths libraries for .NET mentioned on wikipedia - Arbitrary-percision artithmatic page.

I have seen BigNum recommended here before, though the wikipedia link is broken and I can't find the library elsewhere at the moment.

The other option on the page is the C# binding for MPIR.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
6

For the particular problem, computing the square root, you can use Decimal type and Newton's algorithm:

using System;

class Program
{
  public static void Main()
  {
    long x = 4746073226998689451;
    decimal sqrt_x = (decimal)Math.Sqrt(x);
    for (int i = 0; i < 10; ++i)
      sqrt_x = 0.5m * (sqrt_x + x / sqrt_x);
    Console.WriteLine("{0:F16}", sqrt_x);
  }
}

The result is:

2178548421.9999998547197773
kol
  • 27,881
  • 12
  • 83
  • 120
1

Using digit by digit calculation will give you as many digits as you are looking for.

Emond
  • 50,210
  • 11
  • 84
  • 115
  • That would be reinventing the wheel. – Dykam Nov 13 '11 at 18:33
  • @Dykam - Why? I am not suggesting he should code the algorithm himself. If there is an implementation, by all means, use it. – Emond Nov 13 '11 at 18:42
  • That's true, but there are many algorithms for arbitrary calculations, this is just one. I think it would've been more useful to link to an implementation. – Dykam Nov 13 '11 at 18:47
1

instead of double , try big integer and also check out this link

Big numbers with fraction support

Community
  • 1
  • 1
pyCthon
  • 11,746
  • 20
  • 73
  • 135