I'm writing some C# heavy in mathematics. Many lines in sequence using plenty of abs(), min(), max(), sqrt(), etc. Using C# is the plain normal way, I must preface each function with "Math." For example
double x = Math.Min(1+Math.Sqrt(A+Math.Max(B1,B2)),
Math.Min(Math.Cos(Z1),Math.Cos(Z2)));
I'd rather write code like in C:
double x = min(1+sqrt(A+max(B1,B2)), min(cos(Z1), cos(Z2)));
This is easier to read and looks more natural to scientists and engineers. The normal C# way hides the good bits in a fog of "Math."
Is there a way in C# to do this?
After some googling I found an example which lead me to try
using min = Math.Min;
...
double x = min(a,b);
but the "using" statement produced an error, "System.Math.Min(decimal,decimal) is a method but is used like a type" but otherwise this looked like a good solution. (What is 'decimal', anyway?)
Math is a built-in object that has properties and methods for mathematical constants and functions. It's not a function object. Math works with the Number type. It doesn't work with BigInt .
If you really care that much, you can write your own method
private int min(int a, int b)
{
return Math.Min(a, b);
}
if you're ambitious, you can look into doing this with generics
Also, if you want to increase clarity, you can create a new, descriptive variable for each meaningful part, instead of your expression, instead of doing everything inline.
double piece2 = 1+Math.Sqrt(A+Math.Max(B1,B2));
double piece1 = Math.Min(Math.Cos(Z1),Math.Cos(Z2))
double x = min(piece1, piece2);
The only reason I'm naming things piece2
and piece2
, is because I don't actually know what your expression is supposed to calculate. In practice, you should have more meaningful names such as velocity
, or incomeTaxPercentage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With