Category talk:Wren-rat: Difference between revisions
m
→Source code: Now uses Wren S/H lexer.
(→Source code: Various changes or additions to make the Rat class more consistent with the new BigRat class.) |
m (→Source code: Now uses Wren S/H lexer.) |
||
(12 intermediate revisions by the same user not shown) | |||
Line 1:
===Source code===
<
import "./trait" for Comparable
/* Rat represents a rational number as an integral numerator and (non-zero) denominator
Line 8:
*/
class Rat is Comparable {
static maxSafe { Rat.fromInt(9007199254740991) }▼
// Private helper function to check that 'o' is a suitable type and throw an error otherwise.
// Numbers and numeric strings are returned as rationals.
Line 46 ⟶ 43:
static one { Rat.new( 1, 1) }
static two { Rat.new( 2, 1) }
static four { Rat.new( 4, 1) }
static five { Rat.new( 5, 1) }
static six { Rat.new( 6, 1) }
static seven { Rat.new( 7, 1) }
static eight { Rat.new( 8, 1) }
static nine { Rat.new( 9, 1) }
static ten { Rat.new( 10, 1) }
static half { Rat.new( 1, 2) }
static third { Rat.new( 1, 3) }
static quarter { Rat.new( 1, 4) }
static fifth { Rat.new( 1, 5) }
static sixth { Rat.new( 1, 6) }
static seventh { Rat.new( 1, 7) }
static eighth { Rat.new( 1, 8) }
static ninth { Rat.new( 1, 9) }
static tenth { Rat.new( 1, 10) }
Line 90 ⟶ 101:
static fromString(s) {
var n
s = s.trim()
if (!(n = Num.fromString(s))) Fiber.abort("Argument must be a numeric string.")
if (n.isInteger) return Rat.new(n, 1)
return fromDecimalString_(s
}
Line 132 ⟶ 144:
// Basic properties.
num { _n } // numerator
den { _d } // denominator
ratio { [_n, _d] } // a two element list of the above
isInteger {
isPositive { _n > 0 } // checks if positive
isNegative { _n < 0 } // checks if negative
isUnit { _n.abs == 1 } // checks if plus or minus one
isZero { _n == 0 } // checks if zero
// Rounding methods (similar to those in Num class).
Line 146 ⟶ 158:
truncate { Rat.fromInt(toFloat.truncate) } // lower integer, towards zero
round { Rat.fromInt(toFloat.round) } // nearer integer
fraction { this - truncate } // fractional part (same sign as this.num)
// Reciprocal
Line 167 ⟶ 180:
pow(i) {
if (!((i is Num) && i.isInteger)) Fiber.abort("Argument must be an integer.")
if (i == 0) return
var np = _n.pow(i.abs).round
var dp = _d.pow(i.abs).round
return (i > 0) ? Rat.new(np, dp) : Rat.new(dp, np)
}
Line 177 ⟶ 192:
// Other methods.
inc { this + Rat.one } // increment
dec { this - Rat.one } // decrement
abs { (_n >= 0) ?
sign { _n.sign } // sign
// The inherited 'clone' method just returns 'this' as Rat objects are immutable.
Line 194 ⟶ 209:
}
// As above but compares the absolute values of the
compareAbs(other) { this.abs.compare(other.abs) }
Line 206 ⟶ 221:
toMixedString {
var q = _n / _d
var
return sign + q.toString + "_" + r.toString + "/" + _d.toString
}
Line 222 ⟶ 238:
static max(a) { a.reduce { |acc, x| (x > acc) ? x : acc } }
static min(a) { a.reduce { |acc, x| (x < acc) ? x : acc } }
}</syntaxhighlight>
|