vile / scheme / arithmetic_flonum.v
214 lines · 208 sloc · 7.57 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import math
4import math.bits
5
6fn flonum_integral(value f64) bool {
7 return !math.is_inf(value, 0) && !math.is_nan(value) && math.trunc(value) == value
8}
9
10// IEEE decomposition computes the reduced numerator/denominator directly,
11// without allocating exact-number temporaries even for subnormal inputs.
12fn flonum_fraction(value f64, denominator bool) f64 {
13 if math.is_nan(value) { return value }
14 if math.is_inf(value, 0) || value == 0 { return if denominator { 1.0 } else { value } }
15 raw := math.f64_bits(value)
16 encoded := int((raw >> 52) & 0x7ff)
17 mut significand := raw & 0xfffffffffffff
18 mut exponent := -1074
19 if encoded != 0 {
20 significand |= u64(1) << 52
21 exponent = encoded - 1023 - 52
22 }
23 zeroes := bits.trailing_zeros_64(significand)
24 significand >>= zeroes
25 exponent += zeroes
26 if denominator { return if exponent < 0 { math.ldexp(1.0, -exponent) } else { 1.0 } }
27 absolute := if exponent > 0 { math.ldexp(f64(significand), exponent) } else { f64(significand) }
28 return math.copysign(absolute, value)
29}
30
31// Exact conversion is a narrow fallback for quotients close enough to integer
32// boundaries that rounded x/y cannot certify truncation, and for large quotients.
33// The existing canonical exact engine owns all temporary arithmetic.
34fn flonum_division_exact(x f64, y f64, centered bool) !(f64, f64) {
35 a, b := to_exact(real(x))!, to_exact(real(y))!
36 ratio := numeric_divide(a, b)!
37 mut quotient := rounded_number(if y > 0 { .floor } else { .ceiling }, ratio)!
38 mut remainder := numeric_subtract(a, numeric_multiply(quotient, b)!)!
39 absolute_divisor := if y < 0 { numeric_negate(b)! } else { b }
40 if centered && numeric_compare(numeric_multiply(remainder, integer(2))!, absolute_divisor)! >= 0 {
41 quotient = numeric_add(quotient, integer(if y > 0 { 1 } else { -1 }))!
42 remainder = numeric_subtract(remainder, absolute_divisor)!
43 }
44 q := quotient.as_real() or { return math.nan(), math.nan() }
45 r := remainder.as_real() or { return math.nan(), math.nan() }
46 // The corrected report permits unspecified flonums when no representable
47 // results satisfy the defining equations. Choose NaNs deterministically.
48 if numeric_compare(to_exact(real(q))!, quotient)! != 0 || numeric_compare(to_exact(real(r))!, remainder)! != 0 {
49 return math.nan(), math.nan()
50 }
51 return q, if r == 0 { 0.0 } else { r }
52}
53
54fn flonum_division(x f64, y f64, centered bool) !(f64, f64) {
55 if y == 0 || math.is_nan(x) || math.is_nan(y) || math.is_inf(x, 0) || math.is_inf(y, 0) {
56 return math.nan(), math.nan()
57 }
58 // Every small integral binary64 operand and both results are exact here.
59 // This common path calls no arbitrary-precision facility or allocator.
60 if math.abs(x) <= 4503599627370496.0 && math.abs(y) <= 4503599627370496.0 && flonum_integral(x) && flonum_integral(y) {
61 parts := fixnum_division(i64(x), i64(y), centered)!
62 return f64(fixnum_division_quotient(parts)!), f64(parts.remainder)
63 }
64 ratio := x / y
65 absolute := math.abs(ratio)
66 fraction := absolute - math.trunc(absolute)
67 if absolute >= 4503599627370496.0 || fraction <= 0.000000000001 || fraction >= 0.999999999999 {
68 return flonum_division_exact(x, y, centered)
69 }
70 mut quotient := math.trunc(ratio)
71 mut remainder := math.fmod(x, y)
72 if remainder < 0 {
73 original := remainder
74 remainder += math.abs(y)
75 virtual := remainder - original
76 residual := (original - (remainder - virtual)) + (math.abs(y) - virtual)
77 if residual != 0 { return flonum_division_exact(x, y, centered) }
78 quotient -= math.copysign(1.0, y)
79 }
80 if remainder >= math.abs(y) { return flonum_division_exact(x, y, centered) }
81 if centered && remainder >= math.abs(y) - remainder {
82 remainder -= math.abs(y)
83 quotient += math.copysign(1.0, y)
84 }
85 return if quotient == 0 { 0.0 } else { quotient }, if remainder == 0 { 0.0 } else { remainder }
86}
87
88fn flonum_call(op FlonumOperation, args []Value) !Value {
89 name := flonum_native_descriptors[int(op)].name
90 minimum, maximum := match op {
91 .add, .multiply { 0, -1 }
92 .eq, .lt, .le, .gt, .ge { 2, -1 }
93 .max, .min, .subtract, .divide { 1, -1 }
94 .log, .atan { 1, 2 }
95 .div_and_mod, .div, .mod, .div0_and_mod0, .div0, .mod0, .expt { 2, 2 }
96 else { 1, 1 }
97 }
98 check_arity(name, args.len, minimum, maximum)!
99 if op == .flonump { return boolean(args[0].tag == .real) }
100 if op == .real_to_flonum { return real(args[0].as_real()!) }
101 if op == .fixnum_to_flonum {
102 if args[0].tag != .integer { return failure('${name} requires a fixnum') }
103 return real(f64(args[0].whole()))
104 }
105 for value in args { if value.tag != .real { return failure('${name} requires flonums') } }
106 if op in [.eq, .lt, .le, .gt, .ge] {
107 mut result := true
108 for index in 1 .. args.len {
109 a, b := args[index - 1].floating(), args[index].floating()
110 result = result && match op {
111 .eq { a == b }
112 .lt { a < b }
113 .le { a <= b }
114 .gt { a > b }
115 else { a >= b }
116 }
117 }
118 return boolean(result)
119 }
120 if op in [.add, .multiply, .subtract, .divide] {
121 mut result := if op == .multiply { 1.0 } else { 0.0 }
122 mut start := 0
123 if op in [.subtract, .divide] {
124 result = args[0].floating()
125 start = 1
126 if args.len == 1 { return real(if op == .subtract { -result } else { 1.0 / result }) }
127 } else if args.len > 0 {
128 result = args[0].floating()
129 start = 1
130 }
131 for index in start .. args.len {
132 value := args[index].floating()
133 result = match op {
134 .add { result + value }
135 .multiply { result * value }
136 .subtract { result - value }
137 else { result / value }
138 }
139 }
140 return real(result)
141 }
142 x := args[0].floating()
143 if op in [.max, .min] {
144 mut result := x
145 for value in args {
146 n := value.floating()
147 if math.is_nan(n) { return value }
148 if math.is_nan(result) { continue }
149 if n == 0 && result == 0 {
150 negative := if op == .min {
151 math.signbit(n) || math.signbit(result)
152 } else {
153 math.signbit(n) && math.signbit(result)
154 }
155 result = signed_zero(negative)
156 } else if (op == .max && n > result) || (op == .min && n < result) {
157 result = n
158 }
159 }
160 return real(result)
161 }
162 if op in [.integerp, .zerop, .positivep, .negativep, .oddp, .evenp, .finitep, .infinitep, .nanp] {
163 if op in [.oddp, .evenp] && !flonum_integral(x) {
164 return failure('${name} requires integer-valued finite flonums')
165 }
166 return boolean(match op {
167 .integerp { flonum_integral(x) }
168 .zerop { x == 0 }
169 .positivep { x > 0 }
170 .negativep { x < 0 }
171 .oddp { math.fmod(x, 2) != 0 }
172 .evenp { math.fmod(x, 2) == 0 }
173 .finitep { !math.is_inf(x, 0) && !math.is_nan(x) }
174 .infinitep { math.is_inf(x, 0) }
175 else { math.is_nan(x) }
176 })
177 }
178 if op in [.div_and_mod, .div, .mod, .div0_and_mod0, .div0, .mod0] {
179 q, r := flonum_division(x, args[1].floating(), op in [.div0_and_mod0, .div0, .mod0])!
180 if op in [.div, .div0] { return real(q) }
181 if op in [.mod, .mod0] { return real(r) }
182 return numeric_values(real(q), real(r))
183 }
184 mut result := f64(0)
185 match op {
186 .abs { result = math.abs(x) }
187 .numerator { result = flonum_fraction(x, false) }
188 .denominator { result = flonum_fraction(x, true) }
189 .floor { result = math.floor(x) }
190 .ceiling { result = math.ceil(x) }
191 .truncate { result = math.trunc(x) }
192 .round { result = math.round_to_even(x) }
193 .exp { result = math.exp(x) }
194 .log {
195 result = if args.len == 1 {
196 math.log(x)
197 } else {
198 math.log(x) / math.log(args[1].floating())
199 }
200 }
201 .sin { result = math.sin(x) }
202 .cos { result = math.cos(x) }
203 .tan { result = math.tan(x) }
204 .asin { result = math.asin(x) }
205 .acos { result = math.acos(x) }
206 .atan {
207 result = if args.len == 1 { math.atan(x) } else { math.atan2(x, args[1].floating()) }
208 }
209 .sqrt { result = math.sqrt(x) }
210 .expt { result = math.pow(x, args[1].floating()) }
211 else { result = x }
212 }
213 return real(result)
214}
215