Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can modulo deal with big float numbers

Tags:

python

numbers

Hey i'm trying to use modulo with big float numbers but python don't seems to like those big numbers. My goal is to check if the division of 2 integers give me an integer or not (so if division_result%1 == 0 or not)

Example:

x = 3**2
x = x+0.3
x%1
result = 0.3000000000000007 | expected = 0.3
x = 3**199
x = x+0.3
x%1
result = 0.0 |expected = 0.3

How can I improve the precision of the result / or find a clever way to check if the division give me an integer?

like image 355
obchardon Avatar asked Nov 22 '25 08:11

obchardon


2 Answers

not all fractions can be represented exactly as floats. your approach will therefore not work (as expected).

what you might try is the fractions module:

from fractions import Fraction

print(repr(Fraction(25, 5)))  # Fraction(5, 1)

this a way you could use Fraction:

def div_result_int(a, b):

    f = Fraction(a, b)
    return f.denominator == 1

print(div_result_int(a=25, b=5))  # True
print(div_result_int(a=25, b=3))  # False
like image 124
hiro protagonist Avatar answered Nov 24 '25 22:11

hiro protagonist


For integers x and y, the fraction y/x is an integer if and only if y % x == 0. As long as x and y are integers, you don't have to worry about floating point errors or special numerical classes or anything. Just make sure that x and y are actually represented as integers and not floats. And since python can handle large integers, this works for integers longer than 64 bits, e.g:

> x = 17**100
> y = 17**200    
> y % x
0
> (y + 1) % x
1
like image 30
mrip Avatar answered Nov 24 '25 23:11

mrip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!