work on fixed
This commit is contained in:
parent
58f4d4b4f3
commit
481e204323
|
@ -5,14 +5,17 @@ module fixed
|
|||
import math
|
||||
|
||||
const (
|
||||
n_places = 7
|
||||
scale = i64(10 * 10 * 10 * 10 * 10 * 10 * 10)
|
||||
c_n_places = 7
|
||||
c_scale = i64(10 * 10 * 10 * 10 * 10 * 10 * 10)
|
||||
|
||||
c_max = f64(99999999999.9999999)
|
||||
)
|
||||
|
||||
pub struct Fixed {
|
||||
fp i64
|
||||
}
|
||||
|
||||
// New from integer
|
||||
// i: number
|
||||
// n: precision/fraction amount
|
||||
// n moves the decimal point N places left
|
||||
|
@ -20,16 +23,34 @@ pub fn new_i(i i64, n u32) Fixed {
|
|||
mut ii := i
|
||||
mut nn := n
|
||||
|
||||
if nn > n_places {
|
||||
ii = ii / i64(math.pow(10, int(nn-n_places)))
|
||||
nn = n_places
|
||||
if nn > c_n_places {
|
||||
ii = ii / i64(math.pow(10, int(nn-c_n_places)))
|
||||
nn = c_n_places
|
||||
}
|
||||
|
||||
ii = ii * i64(math.pow(10, int(n_places-nn)))
|
||||
ii = ii * i64(math.pow(10, int(c_n_places-nn)))
|
||||
|
||||
return Fixed{fp: ii}
|
||||
}
|
||||
|
||||
// New from floating point
|
||||
pub fn new_f(f f64) Fixed {
|
||||
if math.is_nan(f) || math.is_inf(f, 0) {
|
||||
panic("error: cannot convert value to Fixed: f: $f")
|
||||
}
|
||||
|
||||
if f >= c_max || f <= -c_max {
|
||||
panic("error: cannot convert value to Fixed, it exceeds MAX range: f: $f")
|
||||
}
|
||||
|
||||
mut round := 0.5
|
||||
if f < 0 {
|
||||
round = -0.5
|
||||
}
|
||||
|
||||
return Fixed{fp: i64(f*f64(c_scale) + round)}
|
||||
}
|
||||
|
||||
pub fn (f Fixed) add(b Fixed) Fixed {
|
||||
return Fixed{fp: f.fp + b.fp}
|
||||
}
|
||||
|
@ -39,5 +60,5 @@ pub fn (f Fixed) sub(b Fixed) Fixed {
|
|||
}
|
||||
|
||||
pub fn (f Fixed) float() f64 {
|
||||
return f64(f.fp) / f64(scale)
|
||||
return f64(f.fp) / f64(c_scale)
|
||||
}
|
||||
|
|
|
@ -20,6 +20,23 @@ fn test_fixed() {
|
|||
println("r: $r")
|
||||
println("r: ${r.float()}")
|
||||
}
|
||||
|
||||
{
|
||||
println("floating point:")
|
||||
|
||||
f1 := new_f(1.1)
|
||||
f2 := new_f(2.2)
|
||||
f3 := new_f(0.01)
|
||||
f4 := new_f(-0.01)
|
||||
f5 := new_f(0.0)
|
||||
//f6 := new_f(f64('NaN'))
|
||||
|
||||
println("f1.float: ${f1.float()}")
|
||||
println("f2.float: ${f2.float()}")
|
||||
println("f3.float: ${f3.float()}")
|
||||
println("f4.float: ${f4.float()}")
|
||||
println("f5.float: ${f5.float()}")
|
||||
}
|
||||
|
||||
println("done")
|
||||
}
|
Loading…
Reference in New Issue