Arithmetic/Rational: Difference between revisions

→‎{{header|jq}}: add rround and modify rsqrt to use rround (for speed)
(→‎{{header|jq}}: simpler r_to_decimal/1)
(→‎{{header|jq}}: add rround and modify rsqrt to use rround (for speed))
Line 1,978:
* `rinv` for unary inverse
* `rminus` for unary minus
* `rround` for rounding
 
'''Arithmetic'''
Line 2,013 ⟶ 2,014:
| ($i % $j) as $mod
| ($i - $mod) / $j ;
 
# To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
 
# $p should be an integer or a rational
Line 2,040 ⟶ 2,044:
else r($a;1) == r($b;1)
end;
 
# Input: a Rational
# Output: a Rational with a denominator that has no more than $digits digits
# and such that |rBefore - rAfter| < 1/(10|power($digits)
# where $digits should be a positive integer.
def rround($digits):
if .d | length > $digits
then (10|power($digits)) as $p
| .d as $d
| r($p * .n | idivide($d); $p)
else . end;
 
# Polymorphic; see also radd/0
Line 2,110 ⟶ 2,125:
# Input: non-negative integer or Rational
def rsqrt(precision):
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
r(.;1) as $n
| (precision + 1) as $digits
| def update: rmult( r(1;2); radd(.x; rdiv($n; .x))) | rround($digits);
 
| def update: rmult( r(1;2); radd(.x; rdiv($n; .x)));
 
2,442

edits