a *= b not equivalent to a = a*b
Chris Angelico
rosuav at gmail.com
Fri Aug 26 06:56:46 EDT 2016
On Fri, Aug 26, 2016 at 8:20 PM, mlz <mlzarathustra at gmail.com> wrote:
> I believe there are languages that preserve exact accuracy in this way for rational fractions. I don't know if Python is one of them.
It is, but only if you explicitly request it (due to the performance
impact). Just import it:
#!/usr/bin/python2
import fractions
import sys
FAIL= True if len(sys.argv)>1 else False
def bin(n,k):
rs=1
k=min(k,n-k)
n = fractions.Fraction(n)
for i in range(1,k+1):
if FAIL: rs *= (n-(i-1))/i # these should be the same,
else: rs = rs * (n-(i-1))/i # but apparently are not
return rs
for n in range(10):
for k in range(n+1):
print bin(n,k),
print''
That's the only change you need. The arithmetic will then be done with
ratios of integers, and it'll be exact.
ChrisA
More information about the Python-list
mailing list