C# high precision calculations
Asked Answered
A

4

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?

Alanalana answered 13/11, 2011 at 18:23 Comment(0)
E
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
Evitaevitable answered 13/11, 2011 at 18:35 Comment(0)
F
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.

Felten answered 13/11, 2011 at 18:27 Comment(1)
@GeorgeDuckett - So it is. Do you have a link to a working site?Felten
E
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
Evitaevitable answered 13/11, 2011 at 18:35 Comment(0)
D
1

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

Deutzia answered 13/11, 2011 at 18:27 Comment(3)
That would be reinventing the wheel.Margherita
@Margherita - Why? I am not suggesting he should code the algorithm himself. If there is an implementation, by all means, use it.Deutzia
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.Margherita
S
1

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

Big numbers with fraction support

Sporophyll answered 13/11, 2011 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.