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