precision problem...
I'm doing some scientific calcs that need at least decimal type precision. But the System.Math namespace only deals in doubles. What can I do?
-Devin
Some quick googling shows that their are some high-precision and arbitrary-precision math libraries freely available, although all the ones I've seen are C/C++ libraries. However it's very easy to p/invoke into DLL's, so that shouldn't be a problem if you're working in a managed environment.
You'll probably need a specialized math library with support for its own higher-precision floats.
Here's something I found on Google, but I don't know if it's any good or not.
Here's something I found on Google, but I don't know if it's any good or not.
Great, thanks, I'm thinking about creating my own number from one of those examples. Is there a guide like from ieee or something for doing such? Perhaps in binary?
Ya know I would love to use system.decimal and tried. It worked super but when I went to do a square root, I found there was no such method at that precision. Does anyone know how to do a square root at this precision?
Thanks again,
Devin
Thanks again,
Devin
It only deals in floats/doubles because that's all the CPU can do natively. To perform a square root on a decimal type, you'll have to do it yourself.
One very simple way to do it is to use the Babylonian method. Start with an approximation, and iteratively apply a formula to approximate the square root.
For example:
The more iterations you do, the more accurate the results. Although realistically, I think you'd only need to do maybe 1 or 2 iterations before you reach the maximum precision of the decimal type.
One very simple way to do it is to use the Babylonian method. Start with an approximation, and iteratively apply a formula to approximate the square root.
For example:
class Program{ static Decimal Sqrt(Decimal s) { const int Iterations = 2; Decimal x = (Decimal)Math.Sqrt((Double)s); // Start with a good approximation // Iteratively apply Babylonian method, using the arithmetic mean as an approximation for the geometric mean for (int i = 0; i < Iterations; ++i) { x = (x + s / x) * 0.5m; } return x; } static void Main(string[] args) { Decimal s = 2.0m; Console.WriteLine("Square root of 2"); Console.WriteLine("Double: {0:F28}", Math.Sqrt((Double)s)); Console.WriteLine("Decimal: {0:F28}", Sqrt(s)); Console.WriteLine("Actual value: 1.414213562373095048801688724209698..."); Console.ReadKey(); }}
The more iterations you do, the more accurate the results. Although realistically, I think you'd only need to do maybe 1 or 2 iterations before you reach the maximum precision of the decimal type.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement