-
Notifications
You must be signed in to change notification settings - Fork 2
/
helper.nim
91 lines (70 loc) · 2.53 KB
/
helper.nim
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#
#
# The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
# you may not use this file except in compliance with the License. You may obtain a copy of the
# License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
# ANY KIND, either express or implied. See the License for the specific language governing rights
# and limitations under the License.
#
# Contributors:
# Adrian Veith
#
## The ``helper`` module implements some hopefully useful routines
import math
proc itrunc* (v: float): int {.inline.} =
{.emit: """
return (int)(`v`);
""".}
proc frac* (value: Float): Float {.inline.} =
return value - trunc(value)
#proc ftrunc* (value: Float): Float {.inline.} =
# return if value >= 0 : floor(value) else : ceil(value)
const stellen = [0.00000001,0.0000001,0.000001,0.00001,0.0001,0.001,0.01,0.1,
1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0]
proc round* (x: Float, n: Int): Float =
if (n > 8) or (n < -8) :
return x
else :
let sf = stellen[n + 8]
let xx = x * sf
return (trunc(xx) + trunc(frac(xx) * 2)) / sf
proc roundUp* (x: Float, n: Int): Float =
if (n > 8) or (n < -8) :
return x
else :
let sf = stellen[n + 8]
var xx = x * sf
if frac(xx) > 0 : xx += 1.0
return trunc(xx) / sf
proc roundDown* (x: Float, n: Int): Float =
if (n > 8) or (n < -8) :
return x
else :
let sf = stellen[n + 8]
var xx = x * sf
return trunc(xx) / sf
proc IntPower* (Base: Float, Exponent: Int): Float =
var Y = Abs(Exponent)
var LBase = Base
Result = 1.0
while Y > 0 :
while (Y and 1) == 0 :
Y = Y shr 1
LBase = LBase * LBase
Dec(Y);
Result = Result * LBase
if Exponent < 0 :
Result = 1.0 / Result
when isMainModule:
echo round(4.125, 2), " ", 4.13, " ", round(4.125, 2) - 4.13
echo round(PI, 3), " ", 3.141, " ", round(PI, 3) - 3.142
assert round(PI, 3) == 3.142
echo round(PI, 4)
assert round(PI, 4) == 3.1416
assert roundDown(PI, 4) == 3.1415
echo frac(-3.123), " ", -3.0 + frac(-3.123)
echo 43.9.toInt
echo 43.9.itrunc
echo IntPower(2, 4)