-5

When I run the code

b = 7**7

I get b as 823543

But when I run

b= 823543.0**(1.0/7.0)

It gives me b as 6.999999999999999

If it is something as simple as 4**(1/2) it returns 2.

My question is why doesn't python just return a perfect 7?

Also I was doing this to check if a number can be written n can be written in the form p^q where p>0 and q>1 to do so I did this:

 def isPower(self, A):
    possible = 0 # Integer value to check  if it is possible , 0 assuming it is false initally
    if(A==1):
        return 1
    for i in xrange(2,A-1):
        res = float(A)**(1.0/float(i)) #Check if it has sqaure root or cube root up untill A-1
        if(res.is_integer()): #If taking the power gives me whole number then saying it is possible
            possible = 1
            break
    return possible

This logic fails with higher numbers like 823543 because the power returns a imprecise value how would I solve this?

Sam Thomas
  • 13
  • 3

3 Answers3

1

You're not using Decimals - you're using floats. They trade off accuracy for speed.

Try this;

from decimal import Decimal
b = 7 ** 7  # 823543
a = Decimal(1) / Decimal(7)
b ** a  # returns (for me) Decimal('7.000000000000000000000000004')
Shadow
  • 8,749
  • 4
  • 47
  • 57
0

Why not rounding:

>>> b= 823543**(1/7)
>>> round(b)
7
>>> 

Now you've got 7 (seven)

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 1
    Yes problem is I am checking if a number can be represent in terms of p^q now if I round everything my logic will fail because I am checking if taking the power will give me a perfect integer value represent as float. Rounding it will always result in a perfect integer. – Sam Thomas Oct 26 '18 at 05:49
  • @SamThomas `float(round(b))` for `7.0`. – U13-Forward Oct 26 '18 at 05:50
  • 1
    Yes this will work but when I check if 5 can be represent as p^q , 5^(1/2) is decimal answer and if I round it then my program will assume it can be represent as p^ q so this is why I can't round it. – Sam Thomas Oct 26 '18 at 05:52
  • @SamThomas Ok then don't use mine :-) – U13-Forward Oct 26 '18 at 07:26
0

You should read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

In short: floating point numbers are represented as mantissa and exponent. Something like

0.1234 * 10^1

Where 1234 is the mantissa (the exponent is represented in 2-complement, if I recall correctly)

This means some integer numbers cannot be represented accurately as floats.

You can represent 7 and 823543 exactly as floats, but I don't think that works for 1/7 (don't have a piece of paper at hand): https://www.h-schmidt.net/FloatConverter/IEEE754.html

Also, take into consideration how the n-the root is calculated.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958