Python Forum

Full Version: Irrational number
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
how could i check if a number is irrational
Do you mean with no context whatsoever? You can't do it from a straight up digit, because Python can't just take a digit that goes on forever and even so, you can have a rational number with a million decimal places. You need context like are they taking the root of a number, or if the number being used is some irrational constant like pi, e, omega, etc.
only in python is not possible ?
Please give an example of your input. What kind of number do you want to check?

Any decimal with a finite number of digits is always rational.
def check_number(number):
    if isinstance(number, complex):
        if number.imag == 0.0:
            print("It's a complex number, where the imaginary part is zero")
        else:
            print(f"It's a complex number, where the imaginary part is {number.imag}")
    elif isinstance(number, (int, float)):
        print("Number is an integer or float and has no imaginary part")
    else:
        print(f"`{number}` is not an int nor a float")
Then you can check with some numbers:

check_number((1+0.1j))
check_number((1+1.0j))
check_number((1+0.0j))
check_number(0.0j)
check_number(1.0j)
check_number(1)
check_number(1.5)
check_number("Abc")
The question asks about whether a number is irrational (i.e. that it can't be represented by p/q, where p and q are both integers), not whether the number is real or complex.

(May-07-2020, 11:06 PM)SheeppOSU Wrote: [ -> ]You can't do it from a straight up digit, because Python can't just take a digit that goes on forever

This doesn't make any sense. Digits are single integers, so are rational.
if you check the digits of the number for a period.....?
See this
Irrational, not imaginary. My mistake.

You can't check it from a float, because the float has no information if it's a rational or an irrational number.
A float has a finite precision.

If you get the value 3.141592653589793 as only information, no chance to say if it's rational or irrational.
We know that this value is pi and pi is irrational. From where should the computer know this without any context?

Im not very deep in math, but I think you can maybe detect if a result should be irrational or not after a calculation.
(May-08-2020, 10:17 AM)chpyel Wrote: [ -> ]if you check the digits of the number for a period.....?

Can you give an example?
Pages: 1 2