This question already has answers here:
Is floating point math broken?
(31 answers)
Check if a number is a perfect square
(25 answers)
Closed 5 days ago.
My simple problem is to create a function that determines if a number N can be written as a^n for some given n, i.e. I need to check if N^(1/n) is a whole number. Somehow this function yields wrong results:
def is_power(N, n):
r = float(N) ** ( 1. / float(n) )
return r.is_integer()
For n=2 it works.
For n=3 and N=1,8,27 the function yields True, which is correct. But from then on False, e.g. for 4*4*4=64 or 5*5*5=125. How can I create a working function that finds numbers that are squares/cubes/etc.?
Floating point arithmetic is not exact--see Is floating point math broken?.
So check your answer using exact-integer math. Round r to the nearest integer then see if the power works. This Python 3 code removes some of your redundant type-casting. For Python 2, wrap the calculation of r into an int() typecast (which is not needed for Python 3).
def is_power(N, n):
r = round(N ** (1.0 / n))
return r**n == N
Related
This question already has answers here:
Check if a number is a perfect square
(25 answers)
Closed 11 months ago.
I had a Codility Test, and the question asked me to create a code that listed numbers 1-1000, but at every square number, the program prints
"POWER" instead of the square number. It should look like this:
POWER
2
3
POWER
5
6
7
8
POWER
10
And so on...
I've been trying to solve this, but I can't think of any correct solutions, any help would be much appreciated.
for n in range(1,11):
print(n)
if n == n**2:
print("POWER")
elif n==22:
print("POWER")
elif n==3**2:
print("POWER")
This is the only thing I could think of, but I don't know how I could create a loop for this 1000 times, also the output didn't come out as I wanted it to.
My solution is: calculate sqrt of number, check if it is a whole number using built-in method is_integer() on float object:
import math
for i in range(1000):
if math.sqrt(i).is_integer():
print("POWER")
else:
print(i)
The important things you're missing are the math.sqrt and round functions, which make it very easy to figure out if a number is a perfect square (just check whether the sqrt of the number is round):
import math
for n in range(1,1001):
s = math.sqrt(n)
if s == round(s):
print("POWER")
else:
print(n)
If you weren't allowed to use those functions, another option (which would save you from having to do a guess-and-test iteration for each number) would be to build a set of square numbers within the range you care about and test each n for membership in that set:
squares = {n ** 2 for n in range(1, 32)}
for n in range(1,1001):
if n in squares:
print("POWER")
else:
print(n)
This question already has answers here:
Generate random number between 0.1 and 1.0. Python
(10 answers)
Closed 3 years ago.
I was trying to use numpy.random.uniform to pick a real number on (-1, 1), but I noticed that the upper bound 1 is excluded. Is there any way to include the upper bound as well?
## -------------------- uniform distribution -------------------
def uniform(self, a, b):
"Get a random number in the range [a, b) or [a, b] depending on rounding."
return a + (b-a) * self.random()
If you want to keep by definition the uniform distribution you can force the rounding up to a certain digit with the round function, to have a chance to reach 1 by chance.
round(number, number of digits)
This question already has answers here:
Exponentials in python: x**y vs math.pow(x, y)
(7 answers)
Closed 3 years ago.
I've been trying to solve this problem:
The cube at the bottom will have a volume of n^3, the cube above will
have volume of (n-1)^3 and so on until the top which will have a
volume of 1^3.
You are given the total volume m of the building. Being given m can
you find the number n of cubes you will have to build?
And this is my code
import math
def find_nb(m):
nb = 1
nb_vol = 0
while True:
nb_vol += math.pow(nb, 3)
if (nb_vol == m):
return nb
elif (nb_vol > m):
return -1
nb += 1
Now, when I try to solve for find_nb(2521115597681328384) it returns -1 when it should in fact return 56352. If I change
nb_vol += math.pow(nb, 3)
to
nb_vol += nb ** 3
Everything works correctly. Why?
math.pow always converts it’s arguments to floats first, which are only approximations.
The ** operator uses integers that can never overflow, which means that it always gives a correct result.
This question already has answers here:
What is the best way to compare floats for almost-equality in Python?
(18 answers)
Closed 3 years ago.
Greeting All,
I want to compare float number that but I don't wanna round the number
here is a simple example:
p = 15.0060732
n = 15.00637396
if p == n:
print('=')
if p > n:
print('>')
if p < n:
print('<')
I want p < n , is there any method to hlpe me do that.
* Note: I have a big table that represent these value but it's random so i can't determin the floating point for all table.
any help will be appreciated
Python compares floating-point numbers. Because of the precision, you should use the isclose method of the math module.
If the difference between the two numbers is less than 1e-9, then the two floating point numbers are considered equal.
Math.isclose(a, b, rel_tol=1e-9)
example:
import math
p = 15.0060732
n = 15.00637396
print(math.isclose(1.0, 1.0000000001))
print(math.isclose(1.0, 1.0000000001, rel_tol=1e-10))
print(math.isclose(p, n))
print(math.isclose(p, n, rel_tol=1e-2))
result:
True
False
False
True
This question already has an answer here:
Why is my function using Python time limited in input value magnatude?
(1 answer)
Closed 9 years ago.
I am trying to make a function that calculate the modular exponential MODEXP(a,e,p).
This function takes m and n as a parameters, where p is a prime number at most 2^m and e is 2^n and a is random number less than p.
Here is my code:
import random
def question_3(m,n):
list = []
i = 1
for i in range(2,2**m):
flag=True
for num in list:
if(i%num==0):
flag=False
if flag:
list.append(i)
p = choice(list)
a = randint(1,int(p)-1)
e = pow(2,n)
return pow(a, e, p)
question_3(5,5)
For m and n over 20, the code begins to hang. How do I prevent that?
If you just want to calculate
(modulus of a raised to the power e)modp
or something similar then
I would Highly recommend you this wiki article
In this case maximum number of iteration would be equal to number of bits in binary representation of variable e.