compare float number in python [duplicate] - python

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

Related

Printing binary without trailing 0s? [duplicate]

This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 4 months ago.
Trying to create a small program that takes in positive integers and converts it into reverse binary.
I've gotten this far:
import math
integer = int(input())
while integer > 0:
x = integer % 2
print(int(math.floor(x)), end='')
integer = integer / 2
The problem with this is that the output would have unnecessary trailing 0s. For example, if the input is 12, the output would be 0011000......
I've tried the int function to remove floats, I also tried floor function to round up(albeit I might've done it wrong).
Could the problem be a lack of sentinel value?
It sounds like you have reversed a binary number like this:
def reverse_bits(n):
res = 0
for i in range(n.bit_length(), -1, -1):
if n & (1 << i):
res += 1 << (n.bit_length() - i)
return res
bin(reverse_bits(12)) # '0b110'
You can bit shift to the right, until there is a 1 in the rightmost bit, to remove trailing zeros:
def remove_trailing_zeros(n):
while not n & 1:
n = n >> 1
return n
All together:
bin(remove_trailing_zeros(reverse_bits(12)))
Out[11]: '0b11'
use // instead of / in division
Here is an alternate approach:
integer = 3
print (bin(integer)[2:][::-1])

Codility Test : Square Number [duplicate]

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)

Random number that is divisible by N [duplicate]

This question already has answers here:
Python: Generate random number between x and y which is a multiple of 5 [duplicate]
(4 answers)
Closed 3 years ago.
I want to generate a random number from range [a,b] that is dividsible by N (4 in my case).
I have the solution, but is there a better (more elegant) way to do it?
result = random.randint(a, b)
result = math.ceil(result / 4) * 4
Solutions from here:
Python: Generate random number between x and y which is a multiple of 5
doesn't answer my question since I'll have to implement something like:
random.randint(a, b) * 4;
I'll have to divide original range by 4 and it's less readable then my original solution
A generic solution and an example
import random
def divisible_random(a,b,n):
if b-a < n:
raise Exception('{} is too big'.format(n))
result = random.randint(a, b)
while result % n != 0:
result = random.randint(a, b)
return result
# get a random int in the range 2 - 12, the number is divisible by 3
print(divisible_random(2,12,3))
The first thing coming to my mind is creating a list of all the possible choices using range in the given interval, followed by randomly choosing one value using choice.
So, in this case, for a given a and b,
random.choice(range(a + 4 - (a%4), b, 4))
If a is a perfect multiple of 4, then
random.choice(range(a, b, 4))
Would give you the required random number.
So, in a single generic function, (as suggested in comments)
def get_num(a, b, x):
if not a % x:
return random.choice(range(a, b, x))
else:
return random.choice(range(a + x - (a%x), b, x))
where x is the number whose multiples are required.
As the others have pointed out, your solution might produce out of range results, e.g. math.ceil(15 / 4) * 4 == 16. Also, be aware that the produced distribution might be very far from uniform. For example, if a == 0 and b == 4, the generated number will be 4 in 80% of the cases.
Aside from that, it seems good to me, but in Python, you can also just use the integer division operator (actually floor division, so it's not equivalent to your examlpe):
result = random.randint(a, b)
result = result // 4 * 4
But a more general albeit less efficient method of generating uniform random numbers with specific constraints (while also keeping the uniform distribution) is generating them in a loop until you find a good one:
result = 1
while result % 4 != 0:
result = random.randint(a, b)
Use random.randrange with a step size of n, using a+n-(a%n) as start if a is non-divisible by n, else use a as start
import random
def rand_n(a, b,n):
#If n is bigger than range, return -1
if n > b-a:
return -1
#If a is divisible by n, use a as a start, using n as step size
if a%n == 0:
return random.randrange(a,b,n)
# If a is not divisible by n, use a+n-(a%n) as a start, using n as step size
else:
return random.randrange(a+n-(a%n),b, n)

Python: Function to determine if number is square, cube, etc [duplicate]

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

Python function hangs for large numbers [duplicate]

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.

Categories