decimal – float division by zero Python

decimal – float division by zero Python

Try increasing your precision:

from decimal import Decimal, getcontext

getcontext().prec = 2*n

a = Decimal(a)
b = Decimal(b)
c = a/b

You can do exact arithmetic with fractions using the Fraction class from the standard library:

>>> from fractions import Fraction
>>> n = 2000
>>> p = Fraction(1, 2)
>>> result = p ** n
>>> 1 / result
Fraction(114813069527425452423283320117768198402231770208869520047764273682576626139237031385665948631650626991844596463898746277344711896086305533142593135616665318539129989145312280000688779148240044871428926990063486244781615463646388363947317026040466353970904996558162398808944629605623311649536164221970332681344168908984458505602379484807914058900934776500429002716706625830522008132236281291761267883317206598995396418127021779858404042159853183251540889433902091920554957783589672039160081957216630582755380425583726015528348786419432054508915275783882625175435528800822842770817965453762184851149029376, 1)

The Fraction constructor also accepts a string in decimal format like 0.5 or an exact fraction like 1/2, so you can do p = Fraction(input(...)) instead of float(input(...)).

Note that this will still give you a ZeroDivisionError if the result is actually zero (which happens when p itself is zero).

decimal – float division by zero Python

Try casting pexito as a float on line 17

    intentos = 1/float(pexito)

Leave a Reply

Your email address will not be published.