module scheme import math import math.big const number_primitive_descriptors = [ PrimitiveDescriptor{'exact', Primitive.inexact_to_exact} PrimitiveDescriptor{'inexact', Primitive.exact_to_inexact} PrimitiveDescriptor{'exact-integer?', Primitive.exact_integerp} PrimitiveDescriptor{'exact-integer-sqrt', Primitive.exact_integer_root} PrimitiveDescriptor{'square', Primitive.square} PrimitiveDescriptor{'finite?', Primitive.finite} PrimitiveDescriptor{'infinite?', Primitive.infinite} PrimitiveDescriptor{'nan?', Primitive.nan} PrimitiveDescriptor{'floor/', Primitive.floor_divide} PrimitiveDescriptor{'floor-quotient', Primitive.floor_quotient} PrimitiveDescriptor{'floor-remainder', Primitive.modulo} PrimitiveDescriptor{'truncate/', Primitive.truncate_divide} PrimitiveDescriptor{'truncate-quotient', Primitive.quotient} PrimitiveDescriptor{'truncate-remainder', Primitive.remainder} PrimitiveDescriptor{'complex?', Primitive.complexp} PrimitiveDescriptor{'inexact?', Primitive.inexactp} PrimitiveDescriptor{'zero?', Primitive.zero} PrimitiveDescriptor{'positive?', Primitive.positive} PrimitiveDescriptor{'negative?', Primitive.negative} PrimitiveDescriptor{'odd?', Primitive.odd} PrimitiveDescriptor{'even?', Primitive.even} PrimitiveDescriptor{'abs', Primitive.abs} PrimitiveDescriptor{'max', Primitive.maximum} PrimitiveDescriptor{'min', Primitive.minimum} PrimitiveDescriptor{'quotient', Primitive.quotient} PrimitiveDescriptor{'remainder', Primitive.remainder} PrimitiveDescriptor{'modulo', Primitive.modulo} PrimitiveDescriptor{'gcd', Primitive.gcd} PrimitiveDescriptor{'lcm', Primitive.lcm} PrimitiveDescriptor{'numerator', Primitive.numerator} PrimitiveDescriptor{'denominator', Primitive.denominator} PrimitiveDescriptor{'floor', Primitive.floor} PrimitiveDescriptor{'ceiling', Primitive.ceiling} PrimitiveDescriptor{'truncate', Primitive.truncate} PrimitiveDescriptor{'round', Primitive.round} PrimitiveDescriptor{'rationalize', Primitive.rationalize} PrimitiveDescriptor{'exp', Primitive.exp} PrimitiveDescriptor{'log', Primitive.log} PrimitiveDescriptor{'sin', Primitive.sin} PrimitiveDescriptor{'cos', Primitive.cos} PrimitiveDescriptor{'tan', Primitive.tan} PrimitiveDescriptor{'asin', Primitive.asin} PrimitiveDescriptor{'acos', Primitive.acos} PrimitiveDescriptor{'atan', Primitive.atan} PrimitiveDescriptor{'sqrt', Primitive.sqrt} PrimitiveDescriptor{'expt', Primitive.expt} PrimitiveDescriptor{'exact->inexact', Primitive.exact_to_inexact} PrimitiveDescriptor{'inexact->exact', Primitive.inexact_to_exact} PrimitiveDescriptor{'number->string', Primitive.number_to_string} PrimitiveDescriptor{'string->number', Primitive.string_to_number} PrimitiveDescriptor{'make-rectangular', Primitive.make_rectangular} PrimitiveDescriptor{'make-polar', Primitive.make_polar} PrimitiveDescriptor{'real-part', Primitive.real_part} PrimitiveDescriptor{'imag-part', Primitive.imag_part} PrimitiveDescriptor{'magnitude', Primitive.complex_magnitude} PrimitiveDescriptor{'angle', Primitive.complex_angle}, ]! fn (mut vm VM) install_number_primitives() { for index in 0 .. number_primitive_descriptors.len { entry := &number_primitive_descriptors[index] vm.bind_global(entry.name, procedure_value(&Procedure{ mode: .primitive, name: entry.name, owner: vm.owner, primitive: entry.primitive })) } } fn number_call(p Primitive, args []Value, name string) !Value { if p in [.number_to_string, .string_to_number] { return number_io_call(p, args, name) } if int(p) >= int(Primitive.make_rectangular) { return complex_component_call(p, args, name) } minimum, maximum := match p { .maximum, .minimum { 1, -1 } .gcd, .lcm { 0, -1 } .quotient, .remainder, .modulo, .expt, .rationalize, .floor_quotient, .floor_divide, .truncate_divide { 2, 2 } .atan, .log { 1, 2 } else { 1, 1 } } check_arity(name, args.len, minimum, maximum)! if p == .complexp { return boolean(is_number(args[0])) } if p == .exact_integerp { return boolean(is_exact_integer(args[0])) } mut inexact := false for arg in args { if !is_number(arg) { return failure('expected a number, got ${arg.tag}') } inexact = inexact || is_inexact_number(arg) } for arg in args { if is_nonreal(arg) { return complex_number_call(p, args, name) } } match p { .exact_integer_root { return exact_integer_root(args[0]) } .square { return numeric_multiply(args[0], args[0]) } .finite { return boolean(args[0].tag != .real || (!math.is_nan(args[0].floating()) && !math.is_inf(args[0].floating(), 0))) } .infinite { return boolean(args[0].tag == .real && math.is_inf(args[0].floating(), 0)) } .nan { return boolean(number_is_nan(args[0])) } .floor_quotient, .floor_divide, .truncate_divide { return extended_integer_division(p, args[0], args[1]) } .inexactp { return boolean(inexact) } .zero, .positive, .negative { order := numeric_compare(args[0], integer(0)) or { if number_is_nan(args[0]) { return boolean(false) } return err } return boolean(match p { .zero { order == 0 } .positive { order > 0 } else { order < 0 } }) } .odd, .even { odd := if args[0].tag == .big_integer { args[0].big_integer_pointer().value.is_odd() } else if args[0].tag == .integer { args[0].whole() % 2 != 0 } else { x := integer_real(args[0])! math.fmod(x, 2) != 0 } return boolean(if p == .odd { odd } else { !odd }) } .abs { if args[0].tag == .real { return real(math.abs(args[0].floating())) } return if exact_sign(args[0]) < 0 { numeric_negate(args[0])! } else { args[0] } } .maximum, .minimum { mut best := args[0] for i in 1 .. args.len { order := numeric_compare(args[i], best) or { if number_is_nan(args[i]) { return args[i] } if number_is_nan(best) { return best } return err } if (p == .maximum && order > 0) || (p == .minimum && order < 0) { best = args[i] } } return if inexact { real(best.as_real()!) } else { best } } .quotient, .remainder, .modulo { return integer_division(p, args[0], args[1]) } .gcd, .lcm { return integer_gcd_lcm(p == .lcm, args, inexact) } .numerator, .denominator { exact := to_exact(args[0])! if is_big_exact(exact) { n, d := big_exact_parts(exact)! part := if p == .numerator { n } else { d } return if inexact { inexact_integer_result(part, false)! } else { owned_big_integer(part) } } n, d := exact.as_rational()! part := if p == .numerator { n } else { d } return if inexact { real(f64(part)) } else { integer(part) } } .floor, .ceiling, .truncate, .round { return rounded_number(p, args[0]) } .rationalize { return rationalize_number(args[0], args[1], inexact) } .exact_to_inexact { return real(args[0].as_real()!) } .inexact_to_exact { return to_exact(args[0]) } .expt { return number_power(args[0], args[1]) } .sqrt { if number_is_nan(args[0]) { return args[0] } if numeric_compare(args[0], integer(0))! < 0 { return complex_square_root(args[0]) } if !inexact { if is_big_exact(args[0]) { return big_square_root(args[0]) } n, d := args[0].as_rational()! nr, dr := integer_sqrt(u64(n)), integer_sqrt(u64(d)) if nr * nr == u64(n) && dr * dr == u64(d) { return rational(i64(nr), i64(dr)) } } return real(math.sqrt(args[0].as_real()!)) } .log { if numeric_compare(args[0], integer(0)) or { 1 } < 0 || (args.len == 2 && numeric_compare(args[1], integer(0)) or { 1 } < 0) { return complex_logarithm(args) } return logarithm(args) } .exp, .sin, .cos, .tan, .asin, .acos, .atan { x := args[0].as_real()! if p in [.asin, .acos] && (x < -1 || x > 1) { return complex_transcendental(p, args[0]) } return real(match p { .exp { math.exp(x) } .sin { math.sin(x) } .cos { math.cos(x) } .tan { math.tan(x) } .asin { math.asin(x) } .acos { math.acos(x) } else { if args.len == 2 { math.atan2(x, args[1].as_real()!) } else { math.atan(x) } } }) } else { return failure('unimplemented numeric primitive ${name}') } } } fn integer_real(value Value) !f64 { if is_exact_integer(value) { return value.as_real() } if value.tag == .real { x := value.floating() if !math.is_nan(x) && !math.is_inf(x, 0) && math.floor(x) == x { return x } } return failure('expected an integer') } fn integer_division(p Primitive, a Value, b Value) !Value { if a.tag == .integer && b.tag == .integer { x, y := a.whole(), b.whole() if y == 0 { return failure('division by zero') } // The remainder is representable even when the quotient would overflow. if x == exact_min && y == -1 { if p == .quotient { return owned_big_integer(big.integer_from_u64(u64(1) << 63)) } return integer(0) } if p == .quotient { return integer(x / y) } r := x % y return integer(if p == .modulo && r != 0 && (r < 0) != (y < 0) { r + y } else { r }) } if is_big_exact(a) || is_big_exact(b) { return big_integer_division(p, a, b) } return inexact_integer_division(p, a, b) } fn integer_gcd_lcm(lcm bool, args []Value, inexact bool) !Value { // Validate the whole call before the LCM zero shortcut. A later zero // determines the answer even when a prefix exceeds the numeric range. mut zero := false for arg in args { if !is_integer_number(arg) { return failure('expected an integer') } if lcm && !zero { zero = if arg.tag == .real { arg.floating() == 0 } else { exact_sign(arg) == 0 } } } if zero { return if inexact { real(0) } else { integer(0) } } // Every operand is integral. Reduce its exact magnitude, and round only // the final result. Most calls need only machine integers. mut result := if lcm { u64(1) } else { u64(0) } for arg in args { small := bounded_integer_input(arg) or { return big_gcd_lcm(lcm, args, inexact) } x := magnitude(small) common := gcd(result, x) if lcm { reduced := result / common if reduced > max_u64 / x { return big_gcd_lcm(true, args, inexact) } result = reduced * x } else { result = common } } return division_integer(result, false, inexact) } fn rounded_number(p Primitive, value Value) !Value { if is_big_exact(value) { return big_rounded_number(p, value) } if value.tag == .integer { return value } if value.tag == .real { x := value.floating() if math.is_inf(x, 0) || math.is_nan(x) { return value } return real(match p { .floor { math.floor(x) } .ceiling { math.ceil(x) } .truncate { math.trunc(x) } else { floor := math.floor(x) fraction := x - floor if fraction < 0.5 || (fraction == 0.5 && math.fmod(floor, 2) == 0) { floor } else { floor + 1 } } }) } n, d := value.as_rational()! q, r := n / d, n % d return integer(match p { .floor { if r < 0 { checked_subtract(q, 1)! } else { q } } .ceiling { if r > 0 { checked_add(q, 1)! } else { q } } .truncate { q } else { rem := magnitude(r) complement := u64(d) - rem if rem > complement || (rem == complement && q % 2 != 0) { checked_add(q, if n < 0 { -1 } else { 1 })! } else { q } } }) } fn to_exact(value Value) !Value { if value.tag == .inexact_complex { return complex_to_exact(value) } if value.tag != .real { return value } bits := math.f64_bits(value.floating()) negative := bits >> 63 != 0 biased := int((bits >> 52) & 0x7ff) if biased == 0x7ff { return failure('nonfinite number has no supported exact representation') } mut significand := bits & u64(0x000fffffffffffff) mut exponent := if biased == 0 { -1074 } else { biased - 1023 - 52 } if biased != 0 { significand |= u64(1) << 52 } if significand == 0 { return integer(0) } for exponent < 0 && significand & 1 == 0 { significand >>= 1 exponent++ } if exponent >= 0 { limit := if negative { u64(1) << 63 } else { u64(exact_max) } if exponent >= 64 || significand > (limit >> exponent) { return big_float_exact(significand, exponent, negative) } n := significand << exponent if negative && n == u64(1) << 63 { return integer(exact_min) } return integer(if negative { -i64(n) } else { i64(n) }) } if -exponent > 62 { return big_float_exact(significand, exponent, negative) } n := if negative { -i64(significand) } else { i64(significand) } return rational(n, i64(1) << -exponent) } fn number_power(base Value, exponent Value) !Value { if is_nonreal(base) || is_nonreal(exponent) { return complex_power(base, exponent) } if exponent.tag == .big_integer { return big_number_power(base, exponent) } if base.tag != .real && exponent.tag == .integer { e := exponent.whole() mut factor := if e < 0 { numeric_divide(integer(1), base)! } else { base } mut power := magnitude(e) mut result := integer(1) for power != 0 { if power & 1 != 0 { result = numeric_multiply(result, factor)! } power >>= 1 if power != 0 { factor = numeric_multiply(factor, factor)! } } return result } x, y := base.as_real()!, exponent.as_real()! if x < 0 && math.floor(y) != y { return complex_power(base, exponent) } if x == 0 && y < 0 { return failure('division by zero') } return real(math.pow(x, y)) } fn integer_sqrt(n u64) u64 { if n == 0 { return 0 } mut root := u64(math.sqrt(f64(n))) for root > n / root { root-- } for root + 1 <= n / (root + 1) { root++ } return root } fn rationalize_number(value Value, tolerance Value, inexact bool) !Value { if numeric_compare(tolerance, integer(0))! == 0 { return if inexact { real(value.as_real()!) } else { value } } if numeric_compare(value, integer(0))! == 0 { return if inexact { real(0) } else { integer(0) } } // Integer intervals always have a simplest integer. Work with magnitudes // here so even the minimum exact integer never needs an unrepresentable abs. if value.tag == .integer && tolerance.tag == .integer { x, y := magnitude(value.whole()), magnitude(tolerance.whole()) if x <= y { return integer(0) } difference := x - y return integer(if value.whole() < 0 { -i64(difference) } else { i64(difference) }) } if value.tag == .real && tolerance.tag == .real && math.abs(value.floating()) <= math.abs(tolerance.floating()) { return real(0) } x, y := to_exact(value)!, to_exact(tolerance)! positive := if exact_sign(x) < 0 { numeric_negate(x)! } else { x } radius := if exact_sign(y) < 0 { numeric_negate(y)! } else { y } if numeric_compare(positive, radius)! <= 0 { return if inexact { real(0) } else { integer(0) } } low, high := numeric_subtract(positive, radius)!, numeric_add(positive, radius)! mut result := simplest_positive(low, high)! if exact_sign(x) < 0 { result = numeric_negate(result)! } return if inexact { real(result.as_real()!) } else { result } } fn simplest_positive(lower Value, upper Value) !Value { mut low, mut high := lower, upper mut coefficients := [128]i64{} mut count := 0 mut result := integer(0) for { if is_big_exact(low) || is_big_exact(high) || count == coefficients.len { result = big_simplest_positive(low, high)! break } floor := rounded_number(.floor, low)! if numeric_compare(low, floor)! == 0 { result = floor break } if numeric_compare(floor, rounded_number(.floor, high)!)! < 0 { result = numeric_add(floor, integer(1))! break } coefficients[count] = floor.whole() count++ next_low := numeric_divide(integer(1), numeric_subtract(high, floor)!)! high = numeric_divide(integer(1), numeric_subtract(low, floor)!)! low = next_low } for i := count - 1; i >= 0; i-- { result = numeric_add(integer(coefficients[i]), numeric_divide(integer(1), result)!)! } return result }