views:

77

answers:

2

My very often used extension method is

public static double Pi(double this x) { return Math.PI*x; }

in order to have access to 2.0.Pi() or 0.5.Pi() .. etc

What are some other examples of mathematics related extension methods the people use often?

PS. Just curious.

+3  A: 
public static double Squared(double this x) { return x*x; }
Simpzon
Very good example considering the limitations of the C# syntax to square, cube or raise a power.
jalexiou
My first thought was why not just write x ^ 2 in code, rather than x.Squared()? Fewer characters, and arguably just as clear. But I can see this being useful if, say, a function returns a double... circle.Radius.Squared().PI(). Interesting
James B
A: 

In order to get the creative juices flowing I will offer some more examples...

public static double Raise(double this x, double exponent)
{
    return Math.Pow(x, exponent);
}

public static bool NearZero(double this x, double tolerance)
{
     return Math.Abs(x) <= tolerance;
}

public static double Cap(double this x, double threshold)
{
    return Math.Abs(x)<threshold ? x : threshold*Math.Sign(x);
}

public static double SignOf(double this x, double sense)
{
    return Math.Sign(sense)*Math.Abs(x);
}

public static double ToRadians(double this x) { return Math.PI*x/180; }
public static double ToDegrees(double this x) { return 180*x/Math.PI; }

PS. Thanks @Aaron for posting extensionmethods.net. Unfortunately they have little in terms of math related postings.

jalexiou