| 1 | module scheme |
| 2 | |
| 3 | import math |
| 4 | import math.big |
| 5 | |
| 6 | const number_primitive_descriptors = [ |
| 7 | PrimitiveDescriptor{'exact', Primitive.inexact_to_exact} |
| 8 | PrimitiveDescriptor{'inexact', Primitive.exact_to_inexact} |
| 9 | PrimitiveDescriptor{'exact-integer?', Primitive.exact_integerp} |
| 10 | PrimitiveDescriptor{'exact-integer-sqrt', Primitive.exact_integer_root} |
| 11 | PrimitiveDescriptor{'square', Primitive.square} |
| 12 | PrimitiveDescriptor{'finite?', Primitive.finite} |
| 13 | PrimitiveDescriptor{'infinite?', Primitive.infinite} |
| 14 | PrimitiveDescriptor{'nan?', Primitive.nan} |
| 15 | PrimitiveDescriptor{'floor/', Primitive.floor_divide} |
| 16 | PrimitiveDescriptor{'floor-quotient', Primitive.floor_quotient} |
| 17 | PrimitiveDescriptor{'floor-remainder', Primitive.modulo} |
| 18 | PrimitiveDescriptor{'truncate/', Primitive.truncate_divide} |
| 19 | PrimitiveDescriptor{'truncate-quotient', Primitive.quotient} |
| 20 | PrimitiveDescriptor{'truncate-remainder', Primitive.remainder} |
| 21 | PrimitiveDescriptor{'complex?', Primitive.complexp} |
| 22 | PrimitiveDescriptor{'inexact?', Primitive.inexactp} |
| 23 | PrimitiveDescriptor{'zero?', Primitive.zero} |
| 24 | PrimitiveDescriptor{'positive?', Primitive.positive} |
| 25 | PrimitiveDescriptor{'negative?', Primitive.negative} |
| 26 | PrimitiveDescriptor{'odd?', Primitive.odd} |
| 27 | PrimitiveDescriptor{'even?', Primitive.even} |
| 28 | PrimitiveDescriptor{'abs', Primitive.abs} |
| 29 | PrimitiveDescriptor{'max', Primitive.maximum} |
| 30 | PrimitiveDescriptor{'min', Primitive.minimum} |
| 31 | PrimitiveDescriptor{'quotient', Primitive.quotient} |
| 32 | PrimitiveDescriptor{'remainder', Primitive.remainder} |
| 33 | PrimitiveDescriptor{'modulo', Primitive.modulo} |
| 34 | PrimitiveDescriptor{'gcd', Primitive.gcd} |
| 35 | PrimitiveDescriptor{'lcm', Primitive.lcm} |
| 36 | PrimitiveDescriptor{'numerator', Primitive.numerator} |
| 37 | PrimitiveDescriptor{'denominator', Primitive.denominator} |
| 38 | PrimitiveDescriptor{'floor', Primitive.floor} |
| 39 | PrimitiveDescriptor{'ceiling', Primitive.ceiling} |
| 40 | PrimitiveDescriptor{'truncate', Primitive.truncate} |
| 41 | PrimitiveDescriptor{'round', Primitive.round} |
| 42 | PrimitiveDescriptor{'rationalize', Primitive.rationalize} |
| 43 | PrimitiveDescriptor{'exp', Primitive.exp} |
| 44 | PrimitiveDescriptor{'log', Primitive.log} |
| 45 | PrimitiveDescriptor{'sin', Primitive.sin} |
| 46 | PrimitiveDescriptor{'cos', Primitive.cos} |
| 47 | PrimitiveDescriptor{'tan', Primitive.tan} |
| 48 | PrimitiveDescriptor{'asin', Primitive.asin} |
| 49 | PrimitiveDescriptor{'acos', Primitive.acos} |
| 50 | PrimitiveDescriptor{'atan', Primitive.atan} |
| 51 | PrimitiveDescriptor{'sqrt', Primitive.sqrt} |
| 52 | PrimitiveDescriptor{'expt', Primitive.expt} |
| 53 | PrimitiveDescriptor{'exact->inexact', Primitive.exact_to_inexact} |
| 54 | PrimitiveDescriptor{'inexact->exact', Primitive.inexact_to_exact} |
| 55 | PrimitiveDescriptor{'number->string', Primitive.number_to_string} |
| 56 | PrimitiveDescriptor{'string->number', Primitive.string_to_number} |
| 57 | PrimitiveDescriptor{'make-rectangular', Primitive.make_rectangular} |
| 58 | PrimitiveDescriptor{'make-polar', Primitive.make_polar} |
| 59 | PrimitiveDescriptor{'real-part', Primitive.real_part} |
| 60 | PrimitiveDescriptor{'imag-part', Primitive.imag_part} |
| 61 | PrimitiveDescriptor{'magnitude', Primitive.complex_magnitude} |
| 62 | PrimitiveDescriptor{'angle', Primitive.complex_angle}, |
| 63 | ]! |
| 64 | |
| 65 | fn (mut vm VM) install_number_primitives() { |
| 66 | for index in 0 .. number_primitive_descriptors.len { |
| 67 | entry := &number_primitive_descriptors[index] |
| 68 | vm.bind_global(entry.name, procedure_value(&Procedure{ mode: .primitive, name: entry.name, owner: vm.owner, primitive: entry.primitive })) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | fn number_call(p Primitive, args []Value, name string) !Value { |
| 73 | if p in [.number_to_string, .string_to_number] { return number_io_call(p, args, name) } |
| 74 | if int(p) >= int(Primitive.make_rectangular) { return complex_component_call(p, args, name) } |
| 75 | minimum, maximum := match p { |
| 76 | .maximum, .minimum { 1, -1 } |
| 77 | .gcd, .lcm { 0, -1 } |
| 78 | .quotient, .remainder, .modulo, .expt, .rationalize, .floor_quotient, .floor_divide, |
| 79 | .truncate_divide { |
| 80 | 2, 2 |
| 81 | } |
| 82 | .atan, .log { 1, 2 } |
| 83 | else { 1, 1 } |
| 84 | } |
| 85 | check_arity(name, args.len, minimum, maximum)! |
| 86 | if p == .complexp { return boolean(is_number(args[0])) } |
| 87 | if p == .exact_integerp { return boolean(is_exact_integer(args[0])) } |
| 88 | mut inexact := false |
| 89 | for arg in args { |
| 90 | if !is_number(arg) { return failure('expected a number, got ${arg.tag}') } |
| 91 | inexact = inexact || is_inexact_number(arg) |
| 92 | } |
| 93 | for arg in args { if is_nonreal(arg) { return complex_number_call(p, args, name) } } |
| 94 | match p { |
| 95 | .exact_integer_root { return exact_integer_root(args[0]) } |
| 96 | .square { return numeric_multiply(args[0], args[0]) } |
| 97 | .finite { |
| 98 | return boolean(args[0].tag != .real || (!math.is_nan(args[0].floating()) && !math.is_inf(args[0].floating(), 0))) |
| 99 | } |
| 100 | .infinite { return boolean(args[0].tag == .real && math.is_inf(args[0].floating(), 0)) } |
| 101 | .nan { return boolean(number_is_nan(args[0])) } |
| 102 | .floor_quotient, .floor_divide, .truncate_divide { |
| 103 | return extended_integer_division(p, args[0], args[1]) |
| 104 | } |
| 105 | .inexactp { return boolean(inexact) } |
| 106 | .zero, .positive, .negative { |
| 107 | order := numeric_compare(args[0], integer(0)) or { |
| 108 | if number_is_nan(args[0]) { return boolean(false) } |
| 109 | return err |
| 110 | } |
| 111 | return boolean(match p { |
| 112 | .zero { order == 0 } |
| 113 | .positive { order > 0 } |
| 114 | else { order < 0 } |
| 115 | }) |
| 116 | } |
| 117 | .odd, .even { |
| 118 | odd := if args[0].tag == .big_integer { |
| 119 | args[0].big_integer_pointer().value.is_odd() |
| 120 | } else if args[0].tag == .integer { |
| 121 | args[0].whole() % 2 != 0 |
| 122 | } else { |
| 123 | x := integer_real(args[0])! |
| 124 | math.fmod(x, 2) != 0 |
| 125 | } |
| 126 | return boolean(if p == .odd { odd } else { !odd }) |
| 127 | } |
| 128 | .abs { |
| 129 | if args[0].tag == .real { return real(math.abs(args[0].floating())) } |
| 130 | return if exact_sign(args[0]) < 0 { numeric_negate(args[0])! } else { args[0] } |
| 131 | } |
| 132 | .maximum, .minimum { |
| 133 | mut best := args[0] |
| 134 | for i in 1 .. args.len { |
| 135 | order := numeric_compare(args[i], best) or { |
| 136 | if number_is_nan(args[i]) { return args[i] } |
| 137 | if number_is_nan(best) { return best } |
| 138 | return err |
| 139 | } |
| 140 | if (p == .maximum && order > 0) || (p == .minimum && order < 0) { best = args[i] } |
| 141 | } |
| 142 | return if inexact { real(best.as_real()!) } else { best } |
| 143 | } |
| 144 | .quotient, .remainder, .modulo { return integer_division(p, args[0], args[1]) } |
| 145 | .gcd, .lcm { return integer_gcd_lcm(p == .lcm, args, inexact) } |
| 146 | .numerator, .denominator { |
| 147 | exact := to_exact(args[0])! |
| 148 | if is_big_exact(exact) { |
| 149 | n, d := big_exact_parts(exact)! |
| 150 | part := if p == .numerator { n } else { d } |
| 151 | return if inexact { |
| 152 | inexact_integer_result(part, false)! |
| 153 | } else { |
| 154 | owned_big_integer(part) |
| 155 | } |
| 156 | } |
| 157 | n, d := exact.as_rational()! |
| 158 | part := if p == .numerator { n } else { d } |
| 159 | return if inexact { real(f64(part)) } else { integer(part) } |
| 160 | } |
| 161 | .floor, .ceiling, .truncate, .round { return rounded_number(p, args[0]) } |
| 162 | .rationalize { return rationalize_number(args[0], args[1], inexact) } |
| 163 | .exact_to_inexact { return real(args[0].as_real()!) } |
| 164 | .inexact_to_exact { return to_exact(args[0]) } |
| 165 | .expt { return number_power(args[0], args[1]) } |
| 166 | .sqrt { |
| 167 | if number_is_nan(args[0]) { return args[0] } |
| 168 | if numeric_compare(args[0], integer(0))! < 0 { |
| 169 | return complex_square_root(args[0]) |
| 170 | } |
| 171 | if !inexact { |
| 172 | if is_big_exact(args[0]) { return big_square_root(args[0]) } |
| 173 | n, d := args[0].as_rational()! |
| 174 | nr, dr := integer_sqrt(u64(n)), integer_sqrt(u64(d)) |
| 175 | if nr * nr == u64(n) && dr * dr == u64(d) { return rational(i64(nr), i64(dr)) } |
| 176 | } |
| 177 | return real(math.sqrt(args[0].as_real()!)) |
| 178 | } |
| 179 | .log { |
| 180 | if numeric_compare(args[0], integer(0)) or { 1 } < 0 || (args.len == 2 && numeric_compare(args[1], integer(0)) or { 1 } < 0) { |
| 181 | return complex_logarithm(args) |
| 182 | } |
| 183 | return logarithm(args) |
| 184 | } |
| 185 | .exp, .sin, .cos, .tan, .asin, .acos, .atan { |
| 186 | x := args[0].as_real()! |
| 187 | if p in [.asin, .acos] && (x < -1 || x > 1) { |
| 188 | return complex_transcendental(p, args[0]) |
| 189 | } |
| 190 | return real(match p { |
| 191 | .exp { math.exp(x) } |
| 192 | .sin { math.sin(x) } |
| 193 | .cos { math.cos(x) } |
| 194 | .tan { math.tan(x) } |
| 195 | .asin { math.asin(x) } |
| 196 | .acos { math.acos(x) } |
| 197 | else { |
| 198 | if args.len == 2 { math.atan2(x, args[1].as_real()!) } else { math.atan(x) } |
| 199 | } |
| 200 | }) |
| 201 | } |
| 202 | else { return failure('unimplemented numeric primitive ${name}') } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | fn integer_real(value Value) !f64 { |
| 207 | if is_exact_integer(value) { return value.as_real() } |
| 208 | if value.tag == .real { |
| 209 | x := value.floating() |
| 210 | if !math.is_nan(x) && !math.is_inf(x, 0) && math.floor(x) == x { return x } |
| 211 | } |
| 212 | return failure('expected an integer') |
| 213 | } |
| 214 | |
| 215 | fn integer_division(p Primitive, a Value, b Value) !Value { |
| 216 | if a.tag == .integer && b.tag == .integer { |
| 217 | x, y := a.whole(), b.whole() |
| 218 | if y == 0 { return failure('division by zero') } |
| 219 | // The remainder is representable even when the quotient would overflow. |
| 220 | if x == exact_min && y == -1 { |
| 221 | if p == .quotient { return owned_big_integer(big.integer_from_u64(u64(1) << 63)) } |
| 222 | return integer(0) |
| 223 | } |
| 224 | if p == .quotient { return integer(x / y) } |
| 225 | r := x % y |
| 226 | return integer(if p == .modulo && r != 0 && (r < 0) != (y < 0) { r + y } else { r }) |
| 227 | } |
| 228 | if is_big_exact(a) || is_big_exact(b) { return big_integer_division(p, a, b) } |
| 229 | return inexact_integer_division(p, a, b) |
| 230 | } |
| 231 | |
| 232 | fn integer_gcd_lcm(lcm bool, args []Value, inexact bool) !Value { |
| 233 | // Validate the whole call before the LCM zero shortcut. A later zero |
| 234 | // determines the answer even when a prefix exceeds the numeric range. |
| 235 | mut zero := false |
| 236 | for arg in args { |
| 237 | if !is_integer_number(arg) { return failure('expected an integer') } |
| 238 | if lcm && !zero { |
| 239 | zero = if arg.tag == .real { arg.floating() == 0 } else { exact_sign(arg) == 0 } |
| 240 | } |
| 241 | } |
| 242 | if zero { return if inexact { real(0) } else { integer(0) } } |
| 243 | |
| 244 | // Every operand is integral. Reduce its exact magnitude, and round only |
| 245 | // the final result. Most calls need only machine integers. |
| 246 | mut result := if lcm { u64(1) } else { u64(0) } |
| 247 | for arg in args { |
| 248 | small := bounded_integer_input(arg) or { return big_gcd_lcm(lcm, args, inexact) } |
| 249 | x := magnitude(small) |
| 250 | common := gcd(result, x) |
| 251 | if lcm { |
| 252 | reduced := result / common |
| 253 | if reduced > max_u64 / x { return big_gcd_lcm(true, args, inexact) } |
| 254 | result = reduced * x |
| 255 | } else { |
| 256 | result = common |
| 257 | } |
| 258 | } |
| 259 | return division_integer(result, false, inexact) |
| 260 | } |
| 261 | |
| 262 | fn rounded_number(p Primitive, value Value) !Value { |
| 263 | if is_big_exact(value) { return big_rounded_number(p, value) } |
| 264 | if value.tag == .integer { return value } |
| 265 | if value.tag == .real { |
| 266 | x := value.floating() |
| 267 | if math.is_inf(x, 0) || math.is_nan(x) { return value } |
| 268 | return real(match p { |
| 269 | .floor { math.floor(x) } |
| 270 | .ceiling { math.ceil(x) } |
| 271 | .truncate { math.trunc(x) } |
| 272 | else { |
| 273 | floor := math.floor(x) |
| 274 | fraction := x - floor |
| 275 | if fraction < 0.5 || (fraction == 0.5 && math.fmod(floor, 2) == 0) { |
| 276 | floor |
| 277 | } else { |
| 278 | floor + 1 |
| 279 | } |
| 280 | } |
| 281 | }) |
| 282 | } |
| 283 | n, d := value.as_rational()! |
| 284 | q, r := n / d, n % d |
| 285 | return integer(match p { |
| 286 | .floor { |
| 287 | if r < 0 { checked_subtract(q, 1)! } else { q } |
| 288 | } |
| 289 | .ceiling { |
| 290 | if r > 0 { checked_add(q, 1)! } else { q } |
| 291 | } |
| 292 | .truncate { q } |
| 293 | else { |
| 294 | rem := magnitude(r) |
| 295 | complement := u64(d) - rem |
| 296 | if rem > complement || (rem == complement && q % 2 != 0) { |
| 297 | checked_add(q, if n < 0 { -1 } else { 1 })! |
| 298 | } else { |
| 299 | q |
| 300 | } |
| 301 | } |
| 302 | }) |
| 303 | } |
| 304 | |
| 305 | fn to_exact(value Value) !Value { |
| 306 | if value.tag == .inexact_complex { return complex_to_exact(value) } |
| 307 | if value.tag != .real { return value } |
| 308 | bits := math.f64_bits(value.floating()) |
| 309 | negative := bits >> 63 != 0 |
| 310 | biased := int((bits >> 52) & 0x7ff) |
| 311 | if biased == 0x7ff { return failure('nonfinite number has no supported exact representation') } |
| 312 | mut significand := bits & u64(0x000fffffffffffff) |
| 313 | mut exponent := if biased == 0 { -1074 } else { biased - 1023 - 52 } |
| 314 | if biased != 0 { significand |= u64(1) << 52 } |
| 315 | if significand == 0 { return integer(0) } |
| 316 | for exponent < 0 && significand & 1 == 0 { |
| 317 | significand >>= 1 |
| 318 | exponent++ |
| 319 | } |
| 320 | if exponent >= 0 { |
| 321 | limit := if negative { u64(1) << 63 } else { u64(exact_max) } |
| 322 | if exponent >= 64 || significand > (limit >> exponent) { |
| 323 | return big_float_exact(significand, exponent, negative) |
| 324 | } |
| 325 | n := significand << exponent |
| 326 | if negative && n == u64(1) << 63 { return integer(exact_min) } |
| 327 | return integer(if negative { -i64(n) } else { i64(n) }) |
| 328 | } |
| 329 | if -exponent > 62 { return big_float_exact(significand, exponent, negative) } |
| 330 | n := if negative { -i64(significand) } else { i64(significand) } |
| 331 | return rational(n, i64(1) << -exponent) |
| 332 | } |
| 333 | |
| 334 | fn number_power(base Value, exponent Value) !Value { |
| 335 | if is_nonreal(base) || is_nonreal(exponent) { return complex_power(base, exponent) } |
| 336 | if exponent.tag == .big_integer { return big_number_power(base, exponent) } |
| 337 | if base.tag != .real && exponent.tag == .integer { |
| 338 | e := exponent.whole() |
| 339 | mut factor := if e < 0 { numeric_divide(integer(1), base)! } else { base } |
| 340 | mut power := magnitude(e) |
| 341 | mut result := integer(1) |
| 342 | for power != 0 { |
| 343 | if power & 1 != 0 { result = numeric_multiply(result, factor)! } |
| 344 | power >>= 1 |
| 345 | if power != 0 { factor = numeric_multiply(factor, factor)! } |
| 346 | } |
| 347 | return result |
| 348 | } |
| 349 | x, y := base.as_real()!, exponent.as_real()! |
| 350 | if x < 0 && math.floor(y) != y { |
| 351 | return complex_power(base, exponent) |
| 352 | } |
| 353 | if x == 0 && y < 0 { return failure('division by zero') } |
| 354 | return real(math.pow(x, y)) |
| 355 | } |
| 356 | |
| 357 | fn integer_sqrt(n u64) u64 { |
| 358 | if n == 0 { return 0 } |
| 359 | mut root := u64(math.sqrt(f64(n))) |
| 360 | for root > n / root { root-- } |
| 361 | for root + 1 <= n / (root + 1) { root++ } |
| 362 | return root |
| 363 | } |
| 364 | |
| 365 | fn rationalize_number(value Value, tolerance Value, inexact bool) !Value { |
| 366 | if numeric_compare(tolerance, integer(0))! == 0 { |
| 367 | return if inexact { real(value.as_real()!) } else { value } |
| 368 | } |
| 369 | if numeric_compare(value, integer(0))! == 0 { |
| 370 | return if inexact { real(0) } else { integer(0) } |
| 371 | } |
| 372 | // Integer intervals always have a simplest integer. Work with magnitudes |
| 373 | // here so even the minimum exact integer never needs an unrepresentable abs. |
| 374 | if value.tag == .integer && tolerance.tag == .integer { |
| 375 | x, y := magnitude(value.whole()), magnitude(tolerance.whole()) |
| 376 | if x <= y { return integer(0) } |
| 377 | difference := x - y |
| 378 | return integer(if value.whole() < 0 { -i64(difference) } else { i64(difference) }) |
| 379 | } |
| 380 | if value.tag == .real && tolerance.tag == .real |
| 381 | && math.abs(value.floating()) <= math.abs(tolerance.floating()) { |
| 382 | return real(0) |
| 383 | } |
| 384 | x, y := to_exact(value)!, to_exact(tolerance)! |
| 385 | positive := if exact_sign(x) < 0 { numeric_negate(x)! } else { x } |
| 386 | radius := if exact_sign(y) < 0 { numeric_negate(y)! } else { y } |
| 387 | if numeric_compare(positive, radius)! <= 0 { return if inexact { real(0) } else { integer(0) } } |
| 388 | low, high := numeric_subtract(positive, radius)!, numeric_add(positive, radius)! |
| 389 | mut result := simplest_positive(low, high)! |
| 390 | if exact_sign(x) < 0 { result = numeric_negate(result)! } |
| 391 | return if inexact { real(result.as_real()!) } else { result } |
| 392 | } |
| 393 | |
| 394 | fn simplest_positive(lower Value, upper Value) !Value { |
| 395 | mut low, mut high := lower, upper |
| 396 | mut coefficients := [128]i64{} |
| 397 | mut count := 0 |
| 398 | mut result := integer(0) |
| 399 | for { |
| 400 | if is_big_exact(low) || is_big_exact(high) || count == coefficients.len { |
| 401 | result = big_simplest_positive(low, high)! |
| 402 | break |
| 403 | } |
| 404 | floor := rounded_number(.floor, low)! |
| 405 | if numeric_compare(low, floor)! == 0 { |
| 406 | result = floor |
| 407 | break |
| 408 | } |
| 409 | if numeric_compare(floor, rounded_number(.floor, high)!)! < 0 { |
| 410 | result = numeric_add(floor, integer(1))! |
| 411 | break |
| 412 | } |
| 413 | coefficients[count] = floor.whole() |
| 414 | count++ |
| 415 | next_low := numeric_divide(integer(1), numeric_subtract(high, floor)!)! |
| 416 | high = numeric_divide(integer(1), numeric_subtract(low, floor)!)! |
| 417 | low = next_low |
| 418 | } |
| 419 | for i := count - 1; i >= 0; i-- { |
| 420 | result = numeric_add(integer(coefficients[i]), numeric_divide(integer(1), result)!)! |
| 421 | } |
| 422 | return result |
| 423 | } |
| 424 | |