v / vlib / math / modf.v
27 lines · 25 sloc · 675 bytes · 008aaad99981918c51194d7aaaaaccb4c258f244
Raw
1module math
2
3const modf_maxpowtwo = 4.503599627370496000e+15
4
5// modf returns integer and fractional floating-point numbers
6// that sum to f. Both values have the same sign as f.
7//
8// special cases are:
9// modf(±inf) = ±inf, nan
10// modf(nan) = nan, nan
11pub fn modf(f f64) (f64, f64) {
12 abs_f := abs(f)
13 mut i := 0.0
14 if abs_f >= modf_maxpowtwo {
15 i = f // it must be an integer
16 } else {
17 i = abs_f + modf_maxpowtwo // shift fraction off right
18 i -= modf_maxpowtwo // shift back without fraction
19 for i > abs_f { // above arithmetic might round
20 i -= 1.0 // test again just to be sure
21 }
22 if f < 0.0 {
23 i = -i
24 }
25 }
26 return i, f - i // signed fractional part
27}
28