Include upper bound on numpy random.uniform [duplicate] - python

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)

Related

compare float number in python [duplicate]

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

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

How to split an integer into two integers that when multiplied they give the result of the first number [duplicate]

This question already has answers here:
What is the most efficient way of finding all the factors of a number in Python?
(29 answers)
Closed 6 years ago.
So I've looked everywhere and still can't figure it out.
Basically what I want to do is split number x into two integers that when multiplied they give as result x.
For example:
Input: 10
Output: 5, 2
Is there a way to do this in python? Thanks in advance.
With this you can find all of the possible combinations, including (1, x):
import math # Needed to generate the best range, so you have no repeated combinations.
possible_combinations = [(i, x / i) for i in range(1, int(math.ceil(x**0.5)) + 1) if x % i == 0]
for item in possible_combinations:
print item
Every integer is divisible by itself and by 1. If the integer is composite, it will have at least one other pair of divisors (which may be the same, as in the case of 4, which is divisible by 1,4 and 2,2).
lim = int(math.sqrt(num))
for i in range (1, lim):
if num%i==0:
print(i, int(num/i))

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