Arithmetic/Rational: Difference between revisions
→{{header|jq}}: simpler r_to_decimal/1
(→{{header|jq}}: add r_to_decimal) |
(→{{header|jq}}: simpler r_to_decimal/1) |
||
Line 1,998:
in the case of requal/2.
'''module {"name": "Rational"};'''
<lang jq># a and b are assumed to be non-zero integers
def gcd(a; b):
Line 2,126:
def r_to_decimal: .n / .d;
# Input: a Rational, or {n, d} in general, or
# Output: a string representation of the input as a decimal number.
# If the input is a number, it is simply converted to a string.
# Otherwise, $precision determines the number of digits
# obtained by truncating, but trailing 0s are omitted.
def r_to_decimal($precision):▼
# -0//1 => "0"
▲# Examples assuming $precision is 5:
#
#
# 1/
#
# 1/
#
# 1/
if .n == 0 # captures the annoying case of -0
then "0"
elif .n < 0
else ($m | idivide($n) | tostring + ".") as $quotient▼
then "-" + ((.n = -.n) | r_to_decimal($digits))
else (10|power($digits)) as $p
| (if $nlength > $digits then $n[0:$nlength-$digits] + "." + $n[$nlength-$digits:]
▲ end
▲ end ;
# pretty print ala Julia
|