As both a C programmer and a C# programmer, one of the things I don\'t like abou
ID: 644878 • Letter: A
Question
As both a C programmer and a C# programmer, one of the things I don't like about C# is how verbose math functions are. Every time you would have to use a Sin, cosine, or power function for example, you'd have to prepend the Math static class. This leads to very long code when the equation itself is pretty simple. The problem becomes even worse if you need to typecast data types. As a result, in my opinion, the readability suffers. For example:
double x = -Math.Cos(X) * Math.Sin(Z) + Math.Sin(X) * Math.Sin(Y) * Math.Cos(Z);
As opposed to simply
double x = -cos(X) * sin(Z) + sin(X) * sin(Y) * cos(Z);
This is also the case in other langauges like Java.
I'm not sure if this question actually has a solution, but I would like to know if there are any tricks C# or Java programmers use to improve readability of Math code. I realize however that C#/Java/etc. are not math-oriented languages like MATLAB or similar, so it makes sense. But occasionally one would still need to write math code and it'll be great if one could make it more readable.
Explanation / Answer
You could define local functions that call the global static functions. Hopefully the compiler will inline the wrappers, and then the JIT compiler will produce tight assembly code for the actual operations. For example:
class MathHeavy
{
private double sin(double x) { return Math.sin(x); }
private double cos(double x) { return Math.cos(x); }
public double foo(double x, double y)
{
return sin(x) * cos(y) - cos(x) * sin(y);
}
}
You could also create functions that bundle up common math operations into single operations. This would minimize the number of instances where functions like sin and cos appear in your code, thereby making the clunkiness of invoking the global static functions less noticeable. For example:
public Point2D rotate2D(double angle, Point2D p)
{
double x = p.x * Math.cos(angle) - p.y * Math.sin(angle);
double y = p.x * Math.sin(angle) + p.y * Math.cos(angle);
return new Point2D(x, y)
}
You are working at the level of points and rotations, and the underlying trig functions are buried.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.