diff --git a/Modelica/Math/nearestInteger.mo b/Modelica/Math/nearestInteger.mo new file mode 100644 index 0000000000..bda058567c --- /dev/null +++ b/Modelica/Math/nearestInteger.mo @@ -0,0 +1,44 @@ +within Modelica.Math; +function nearestInteger "Convert real number to nearest integer value" + extends Modelica.Icons.Function; + + input Real r "Real number to convert to integer"; + output Integer i "Integer value, which is closest to the given real number"; + +algorithm + i :=if (r > 0) then integer(floor(r + 0.5)) else integer(ceil(r - 0.5)); + + annotation (Documentation(info=" + +

Syntax

+
+Math.nearestInteger(r);
+
+ +

Description

+

+The input value \"r\" of type Real is converted to the closest Integer value \"i\", +using the round half away from zero rule with the equation: +

+
+i = integer( floor( r + 0.5 ) )  for  r > 0;
+i = integer(  ceil( r - 0.5 ) )  for  r < 0;
+
+ +

Example

+
+import Modelica.Math;
+Math.nearestInteger(0.4);                     // = 0
+Math.nearestInteger(0.5);                     // = 1
+Math.nearestInteger(-0.4);                    // = 0
+Math.nearestInteger(-0.5);                    // = -1
+
+ +

Note

+ +

+This function does the same conversion as the block +RealToInteger. +

+")); +end nearestInteger; diff --git a/Modelica/Math/package.order b/Modelica/Math/package.order index c1f671ddc0..2e18c9335a 100644 --- a/Modelica/Math/package.order +++ b/Modelica/Math/package.order @@ -10,6 +10,7 @@ FastFourierTransform Icons isEqual isPowerOf2 +nearestInteger sin cos tan diff --git a/ModelicaTest/Math.mo b/ModelicaTest/Math.mo index 26d07b7cc9..df9d43d692 100644 --- a/ModelicaTest/Math.mo +++ b/ModelicaTest/Math.mo @@ -32,6 +32,14 @@ extends Modelica.Icons.ExamplesPackage; assert(Math.isPowerOf2(1), "isPowerOf2(1) is wrong"); assert(Math.isPowerOf2(4), "isPowerOf2(4) is wrong"); assert(not Math.isPowerOf2(9), "isPowerOf2(9) is wrong"); + + assert(Math.nearestInteger(1.4999)==1, "nearestInteger(1.4999) failed"); + assert(Math.nearestInteger(1.5)==2, "nearestInteger(1.5) failed"); + assert(Math.nearestInteger(-1.4999)==-1, "nearestInteger(-1.4999) failed"); + assert(Math.nearestInteger(-1.5)==-2, "nearestInteger(-1.5) failed"); + // Test deactivated - would fail with current implementation + // assert(Math.nearestInteger(1.49999999999999999999)==1, "nearestInteger border case failed"); + ok:=true; end ScalarFunctions;