-1

How can I do Math.sqrt(); and get a set number of decimal places?

Example code (kind of):

  Console.WriteLine(getSqrt(2, 100));
  static string getSqrt(double inVal, int inLenght)
  {
       return ((Math.Sqrt(inVal)).ToString()); // inLenght is number of decimal places
  }

Currently with math.Sqrt I get 13 decimal places, but I want to be able get 100 or 1000 or more, (also want it as string).

I have looked a bit at BigIntegers (System.Numerics) but idk.

Patrik Fröhler
  • 1,221
  • 1
  • 11
  • 38
  • do a google search on `string.Format` and using it with formatting decimals tons of examples out there – MethodMan May 18 '17 at 22:04
  • The problem is that you can only go so far with double/float/decimal datatypes. If you want to get arbitrary number of decimal places then you have to get the appropriate data structures. As you have identified, there are big integer classes, however, you would be more interested in something that has the capacity to store high precision values (Integer vs Floating point). This can be done in other environment such as Matlab, R, Mathematica. – windrunn3r.1990 May 18 '17 at 22:07
  • @MethodMan pretty sure string-formatting isn't going to solve the issue of 100's or 1000's of decimal places with a double. You'll need some sort of arbitrary-percision package, like Java's BigDecimal, and you'll likely have to roll your own Newton Raphson for square-roots maybe... – juanpa.arrivillaga May 18 '17 at 22:08
  • 1
    https://www.bing.com/search?q=c%23+bigfloat ? – Alexei Levenkov May 18 '17 at 22:10
  • I have tried W3b.Sine but It don't have square root. – Patrik Fröhler May 18 '17 at 22:13
  • Or if you want Python: `import decimal; decimal.getcontext().prec = 100; print(decimal.Decimal('1223232.232').sqrt())` :) – juanpa.arrivillaga May 18 '17 at 22:13
  • N[Sqrt[2], 10000] works on wolfram alpha, and is exactly the type of result I want to achieve, but with c# and need to be as high performance as possible, so I can run as many sqrt as possible per sec. But guessing from the comments I assume no one have a good answer on how to do it. – Patrik Fröhler May 18 '17 at 23:12
  • 1
    Use [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method#Square_root_of_a_number). It only requires a few lines of code. – r3mainer May 18 '17 at 23:18
  • You should use a Taylor series. – user3344003 May 19 '17 at 13:06

1 Answers1

0

Using the Extreme Optimization Numerical Libraries for .NET Professional 6.0 (60 Day Trial Version), but feels a bit overkill for just needing a square root function.

But it works, for now...

using Extreme.Mathematics; 

Console.WriteLine(BigFloat.Sqrt(2,AccuracyGoal.Absolute(10000)));
Patrik Fröhler
  • 1,221
  • 1
  • 11
  • 38