views:

835

answers:

2

FORTRAN provides several functions to convert a double precision number to an integral value. The method used for truncation/rounding differs. I am converting complex scientific algorithms which use these.

According to FORTRAN documentation:
aint(x) returns the integral value between x and 0, nearest x.
anint(x) returns the nearest integral value to x, except halfway cases are rounded to the integral value larger in magnitude.
nint(x) converts x into int format rounding to the nearest int value, except halfway cases are rounded to the int value larger in magnitude.

Does anyone have an implementation of these in C#? It might be tricky getting it right.

(int)x appears to match aint()
Convert.ToInt32(x) does not match any of the above.
Trunc(x) does not match any of the above.
Round(x) might match anint or nint.

The difference between anint and nint seems to be the return type, where anint returns a double precision value but nint returns an integer. Both are used (acutal sample):
DOUBLE PRECISION A, B, C, D, E, F, G
... values set here ...
F = ANINT(A-B) + ANINT(C-D) + ANINT(B+D-E)
G = NINT(F) + 1D0;
Perhaps a FORTRAN expert could help clarify why the author chose to use both (I am assuming it was intentional).

+2  A: 

From your definitions of the calls, nint and anint are provided by Math.Round using MidpointRounding.AwayFromZero.

For aint, an explicit cast from double to int will achieve that result.

Jeff Yates
documentation here:http://msdn.microsoft.com/en-us/library/system.math.round.aspxDid not exist in early versions of C#.
Mark T
Thanks, Mark. I wasn't aware of its absence in earlier editions.
Jeff Yates
+1  A: 

From what I can see, aint() is just Math.Floor().

For the other two, I think you are right that the only difference is the return type: nint() returns an actual integer, while anint() returns a double (fortran: real) that happens to have an integral value.

Joel Coehoorn
Floor() does not behave like aint() for negative numbers.
Mark T