Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#

An introduction to numerical programming in C#

Rate me:
Please Sign up or sign in to vote.
4.63/5 (26 votes)
26 Jun 2014BSD4 min read 69.3K   52   6
Some of the first things you need to know when writing numerical software in C#.

Introduction

The first time you write numerical software in a new programming language, you ask the following questions:

  • How do I import the standard math library?
  • How do I use common math functions?
  • What math functions are included and which ones will I need to write or find elsewhere?

For example, in C, you need to add #include "math.h" before you call any math functions. Then you can call functions by their traditional names. To find the sine of a number x, for example, you simply call sin(x).

In Python, you need to add import math to the top of your source file. Math functions typically have the same names as in C, but the functions are methods on a class called math rather than global functions. Not as many math functions are available as in C, but you can use SciPy to access an enormous collection of math functions.

What do you have to do in C#? Any gotchas? What's available and what's not?

C# mathematical functions

In C#, mathematical functions are static methods on the System.Math class. You don't have to add any references. You probably want to add using System; at the top of your files so you can just type Math rather than System.Math every time you need to call a method.

Functions in System.Math follow .NET naming conventions, and so start with capital letters. Otherwise, function names for mathematical functions are often the same as in C. For example, the C functions exp and cos are Math.Exp and Math.Cos in C#. However, there are a few differences. The following table compares C and C# function names.

C System.Math
acos Acos
asin Asin
atan Atan
ceil Ceiling
cos Cos
cosh Cosh
exp Exp
fabs Abs
floor Floor
fmod IEEERemainder
log Log
log10 Log10
pow Pow
sin Sin
sinh Sinh
sqrt Sqrt
tan Tan
tanh Tanh

Notice that there are three exceptions to the pattern that C# function names are simply capitalizations of C names: Ceiling, Abs, and IEEERemainder.

There are a couple functions from the C math library that are methods on double rather than on System.Math. The double class has methods IsNan and IsFinite corresponding to the methods isnan and isfinite in math.h. (Visual Studio's version of math.h has a function _isnan, but does not have a function corresponding to isfinite.)

Numeric limits

Numeric limits in C# have a couple surprises for C and C++ programmers.

In C#, double.MaxValue is the largest finite value of a double, corresponding to DBL_MAX in C. However, the constant double.MinValue is not the same as DBL_MIN in C. Also, the constant double.Epsilon does not correspond to DBL_EPSILON in C. This may be the biggest pitfall for programmers coming from C or related languages.

The following code prints the numeric limits from float.h:

C++
printf("DBL_MAX     = %g\n", DBL_MAX);
printf("DBL_MIN     = %g\n", DBL_MIN);
printf("DBL_EPSILON = %g\n", DBL_EPSILON);

The output is as follows:

DBL_MAX     = 1.79769e+308
DBL_MIN     = 2.22507e-308
DBL_EPSILON = 2.22045e-016

(The constants DBL_MAX, DBL_MIN, and DBL_EPSILON correspond to the return values of the max, min, and epsilon methods on numeric_limits<double> in C++.)

Here is the analogous C# code:

C#
Console.WriteLine("double.MaxValue = {0}", double.MaxValue);
Console.WriteLine("double.MinValue = {0}", double.MinValue);
Console.WriteLine("double.Epsilon  = {0}", double.Epsilon);

The output of the C# code is as follows:

double.MaxValue = 1.79769313486232E+308
double.MinValue = -1.79769313486232E+308
double.Epsilon  = 4.94065645841247E-324

In short, C and C# have the same idea of “max”, but they have different ideas of “min” and “epsilon”.

The constants DBL_MIN and double.MinValue are different because they are minimizing over different ranges. DBL_MIN is the smallest positive value of a normalized double, and double.MinValue in C# is the smallest (i.e., most negative) finite value of a double.

The C constant DBL_EPSILON is the smallest positive double precision number x such that 1 + x does not equal 1. Typically, a double has about 15 figures of precision, and so DBL_EPSILON is of the order of 10-16. (For a more precise description, see Anatomy of a floating point number.)

C# has no counterpart to DBL_EPSILON. The constant double.Epsilon in C# is something like the C constant DBL_MIN. double.Epsilon is the smallest possible positive value of a double, including denormalized values. DBL_MIN is the smallest positive value of a double restricted to normalized values.

Missing functionality

The list of mathematical functions in C# is minimal. Some of the missing functionality can be filled in easily. For example, System.Math does not include the inverse hyperbolic functions asinh, acosh, or atanh. But these can be computed via the following identities:

  • asinh(x) = log(x + sqrt(x2 + 1))
  • acosh(x) = log(x + sqrt(x2 - 1))
  • atanh(x) = (log(1+x) - log(1-x))/2

However, other mathematical functions that you might expect will not be as easy to supply. For example, C# has no error function erf(x). This function is not trivial to implement, though this link provides stand-alone C# code for erf.

Conclusions

In summary:

  • Math functions are members of the System.Math class.
  • Function names are capitalizations of traditional names, with a few exceptions.
  • The numeric limit constants for doubles look deceptively like C counterparts, but are not the same.
  • C# does not come with support for advanced math functions.

Related CodeProject articles

History

  • June 7, 2010: Initial version.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
President John D. Cook Consulting
United States United States
I work in the areas of applied mathematics, data analysis, and data privacy.

Check out my blog or send me a note.

 


Comments and Discussions

 
GeneralMy vote of 5 Pin
User 1106097912-Mar-16 4:30
User 1106097912-Mar-16 4:30 
QuestionC# Normal cumulative and inverse normal cumulative (Phi and invPhi) Pin
douglas12523-Feb-12 5:26
douglas12523-Feb-12 5:26 
QuestionOLS regression Pin
zedTaha26-Nov-11 22:01
zedTaha26-Nov-11 22:01 
GeneralC# Maths Packages Pin
Nonpareil15-Jun-10 6:16
Nonpareil15-Jun-10 6:16 
Generaldouble.Epsilon Pin
Günther M. FOIDL15-Jun-10 3:02
Günther M. FOIDL15-Jun-10 3:02 
Hello John,

as always it's nice to read your articles!

It's very good that you pointed out that double.Epsilon doesn't represent the value of epsilon as in numerics usual. In the past I had some serious discussion convincing people that double.Epsilon != epsilon in the sense of 1 = 1 + epsilon.

Thanks for the article!

Cheers
Günther
Generalgood article Pin
Rozis9-Jun-10 13:01
Rozis9-Jun-10 13:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.