forked from modelica/ModelicaStandardLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nearestInteger.mo
50 lines (42 loc) · 1.66 KB
/
nearestInteger.mo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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="<html>
<h4>Syntax</h4>
<blockquote><pre>
Math.<strong>nearestInteger</strong>(r);
</pre></blockquote>
<h4>Description</h4>
<p>
The input value \"r\" of type Real is converted to the closest Integer value \"i\",
using the <i>round half away from zero</i> rule with the equation:
</p>
<blockquote><pre>
i = <strong>integer</strong>( <strong>floor</strong>( r + 0.5 ) ) for r > 0;
i = <strong>integer</strong>( <strong>ceil</strong>( r - 0.5 ) ) for r < 0;
</pre></blockquote>
<h4>Example</h4>
<blockquote><pre>
import Modelica.Math;
Math.nearestInteger(0.4); // = 0
Math.nearestInteger(0.5); // = 1
Math.nearestInteger(-0.4); // = 0
Math.nearestInteger(-0.5); // = -1
Math.nearestInteger(0.3999999999999999+0.1); // = 0
Math.nearestInteger(1.39999999999999999+0.1); // = 1 (errorneous border case, see note below)
</pre></blockquote>
<h4>Note</h4>
<p>
This function does the same conversion as the block
<a href=\"modelica://Modelica.Blocks.Math.RealToInteger\">RealToInteger</a>.
</p>
<p>
The underlying equation is simple, but not always correct. Due to floating point arithmetic some border cases
are not converted correct, like shown in the example above.
</p>
</html>"));
end nearestInteger;