Search code examples
pythonintegerdiophantine

How to check if number is integer number, with good precision?


There is similar question: Checking whether a variable is an integer or not, but I see no answer to my question.

I mean, I was fighting with big numbers recently, so friend of mine suggested me to install Python. I opened it today, so that I can compute big numbers and have good precision, but... how to use this precision? I mean, if I do something like pow(31,123) it works fine, but if I want to check if number is integer, I get:

>>> (4.00000000000001).is_integer()
False
>>> (4.000000000000001).is_integer()
False
>>> (4.0000000000000001).is_integer()
True
>>> (4.00000000000000001).is_integer()
True

I wanted to write simple loop to find some solutions of diophantine-equation, where I need to take square root from the very big number and check if it is integer number, but now I am in pinch. Can someone help me or give me an advice how to achieve better precision?

Example:

For example: $ 2x^2 = 1 + y^31 $, where x,y are integer numbers. My idea is to make loop, where I increment y (starting from 1), add 1, divide by 2, take square root, and then it must be integer to satisfy the equation. This is why I need it.


Solution

  • You can check if a given number is a square of an integer using the code below:

    def is_square(x):
        s = int(sqrt(x) + 0.5)
        return s * s == x
    

    Similar approach can be used for a diophantine equation. Just convert y found for a given x to int (y = int(y + 0.5)) and then check if diophantine equation is true for found given x and y