only for RuBoard - do not distribute or recompile |
C# and the FCL provide a rich set of features that make math-oriented programming easy and efficient.
This section identifies some of the most common types applicable to math programming and demonstrates how to build new math types. The types mentioned in this section exist in the Systemnamespace.
C# has many useful features for math and can even build custom mathematical types. Operator overloading allows custom mathematical types, such as complex numbers and vectors, to be used in a natural way. Rectangular arrays provide a fast and easy way to express matrices. Finally, structs allow the efficient creation of low-overhead objects. For example:
struct Vector { float direction; float magnitude; public Vector(float direction, float magnitude) { this.direction = direction; this.magnitude = magnitude; } public static Vector operator *(Vector v, float scale) { return new Vector(v.direction, v.magnitude * scale); } public static Vector operator /(Vector v, float scale) { return new Vector(v.direction, v.magnitude * scale); } // ... } class Test { static void Main( ) { Vector [,] matrix = {{new Vector(1f,2f), new Vector(6f,2f)}, {new Vector(7f,3f), new Vector(4f,9f)}}; for (int i=0; i<matrix.GetLength(0); i++) for (int j=0; j<matrix.GetLength(1); j++) matrix[i, j] *= 2f; } }
The decimal datatype is useful for financial calculations, since it is a base10 number that can store 28 to 29 significant figures (see Section 2.2.5.3).
The checked operator allows integral operations to be bounds checked (see Section 2.4.2).
The Math class provides static methods and constants for basic mathematical purposes. All trigonometric and exponential functions use the double type, and all angles use radians. For example:
using System; class Test { static void Main( ) { double a = 3; double b = 4; double C = Math.PI / 2; double c = Math.Sqrt (a*a+b*b-2*a*b*Math.Cos(C)); Console.WriteLine("The length of side c is "+c); } }
The Random class produces pseudo-random numbers and may be extended if you require greater randomness (for cryptographically strong random numbers, see the System.Security.Cryptography.RandomNumberGenerator class). The random values returned are always between a minimum (inclusive) value and a maximum (exclusive) value. By default, the Random class uses the current time as its seed, but a custom seed can also be supplied to the constructor. Here's a simple example:
Random r = new Random( ); Console.WriteLine(r.Next(50)); // return between 0 and 50
only for RuBoard - do not distribute or recompile |