1

I have written the following code in Python 3:

import math

class Solution:
    def isPowerOfTwo(self, n: int):
        
        y = math.log(n,2)
        z = int(y)
        return z==y

I know there are alternate algorithms to find the answer.

I want to understand:

As I see it, mathematically there is nothing wrong with my solution. The solution fails for some values because of the way python calculates logs.

Is there a way I can still make it work?

Also as a beginner programmer do I also need to consider the limitations of python (esp when it comes to floating points) and implement an alternative algorithm even my original algorithm is correct. If so what are the other pitfalls I might run into when writing algorithms which I think are correct but won't work as I want them to because of how the program implements them?

Steve austin
  • 339
  • 2
  • 15
  • 1
    `return True if (n&(n-1)==0) else False`, your case will fail when n is 0. you need to handle that case, for rest i think it would work fine. – sahasrara62 Aug 24 '21 at 12:23
  • I know that works; I am trying to understand how to make the log solution work – Steve austin Aug 24 '21 at 12:26
  • 1
    You could define a threshold of inaccuracy that is still okay instead of an equals check – lucidbrot Aug 24 '21 at 12:39
  • Although the `n&(n-1)` solution might look like a trick, and feel less satisfying to a mathematician than using `math.log`, it is a much better solution in many respects. Numbers are encoded in binary on computers, so you should make use of that. Checking whether a floating-point number is an integer or not is bad; floating-point types can only represent numbers of the shape `n/2**m` with n and m integers; (the binary equivalent of decimal numbers), **not** all real numbers (and not even all rational numbers). – Stef Aug 24 '21 at 13:33
  • 2
    I recommend reading the excellent [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html#680) – Stef Aug 24 '21 at 13:33
  • 1
    Testing for equality between floating-point numbers in general is a bad idea; the python interpreter doesn't complain, but C and C++ compilers will generally produce a warning if you attempt to do that (unless you compile without the -Wfloat-equal flag). – Stef Aug 24 '21 at 13:36

0 Answers0