Math.Sqrt Method
This page was last reviewed on Mar 21, 2022.
Dot Net Perls
Math.Sqrt. This C# method computes a square root value at runtime. A square root is the number that, when multiplied by itself, equals the original number.
Method details. Sqrt is a slower computation. It can be cached for a performance boost. Sqrt() in C# is a public static method on the Math class.
Example. The Math.Sqrt method is called with a double argument. In this program, the integer arguments to Math.Sqrt are converted to doubles at compile-time.
And The Sqrt method returns another double. In C# the double is an 8-byte type and it supports floating point data.
Detail We generate a simple cache or lookup table of the results of Sqrt() for some integer keys. This is a double array.
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]); } }
1 1.4142135623731 1.73205080756888 2 1 1.4142135623731 1.73205080756888 2
Lookup tables. Here is an effective tip for performance optimization. You can cache the results of functions such as Sqrt in arrays or other lookup structures.
Tip When the original method call is slow, this sometimes yields impressive performance boosts.
So To get the Sqrt(1), you can instead use lookup[1]. This reduces a complex mathematical routine to a simple memory access.
Summary. The C# Sqrt method is sometimes useful. But its logic can be slow. It can be effectively stored in an array (or other lookup table) and then instantly fetched.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 21, 2022 (image).
© 2007-2024 Sam Allen.