Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Euler #26, how to convert rational number to string with better precision?

I want to get 1/7 with better precision, but it got truncated. How can I get better precision when I convert a rational number?

>>> str(1.0/7)[:50]
'0.142857142857'
like image 863
grokus Avatar asked Nov 12 '09 03:11

grokus


2 Answers

Python has a built-in library for arbitrary-precision calculations: Decimal. For example:

>>>from decimal import Decimal, getcontext
>>>getcontext().prec = 50
>>>x = Decimal(1)/Decimal(7)
>>>x
Decimal('0.14285714285714285714285714285714285714285714285714')
>>>str(x)
'0.14285714285714285714285714285714285714285714285714'

Look at the Python Decimal documentation for more details. You can change the precision to be as high as you need.

like image 177
Daniel G Avatar answered Sep 20 '22 23:09

Daniel G


You could multiply the numerator by a large 10^N and stick with arbitrary-precision integers.

EDIT

i mean:

> def digits(a,b,n=50): return a*10**n/b
.
> digits(1,7)
14285714285714285714285714285714285714285714285714L

Python's integers are arbitrary precision. Python's floats are never arbitrary precision. (you'd have to use Decimal, as another answer has pointed out)

like image 27
Jimmy Avatar answered Sep 18 '22 23:09

Jimmy