C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# program that uses Math.Sqrt
using System;
class Program
{
static double[] _lookup = new double[5];
static void Main()
{
// Compute square roots by calling Math.Sqrt.
double a = Math.Sqrt(1);
double b = Math.Sqrt(2);
double c = Math.Sqrt(3);
double d = Math.Sqrt(4);
// Store square roots in lookup table.
var lookup = _lookup;
lookup[1] = a;
lookup[2] = b;
lookup[3] = c;
lookup[4] = d;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
Console.WriteLine(lookup[1]);
Console.WriteLine(lookup[2]);
Console.WriteLine(lookup[3]);
Console.WriteLine(lookup[4]);
}
}
Output
1
1.4142135623731
1.73205080756888
2
1
1.4142135623731
1.73205080756888
2
So: To get the Sqrt(1), you can instead use lookup[1]. This reduces a complex mathematical routine to a simple memory access.
Tip: You can research this by studying the memory hierarchy. You can also use the Math.Pow method to reverse Sqrt.
Locality of ReferenceMath.Pow