Random number generation with a x chance of it being 1 [duplicate] - python

This question already has answers here:
A weighted version of random.choice
(28 answers)
Closed 6 years ago.
I am using a number generator currently using the code below
from random import randint
print(randint(0,1))
which while it works, i need to generate either 0 or 1 but i need the generator to generate 1 with a x (say 80%) probability
how can i achieve this effectively in python ?

random.random() will return a random decimal between 0 and 1. Use this value to determine your choice:
from random import random
print(0 if random() > 0.8 else 1)
and of course, 0.8 can be replaced with any probability (60% -> 0.6).
As #TigerhawkT3 noted, you might use the shorter version random() < 0.8 to generate a boolean variable, if you want to do an action based on that random probability, like
x = random() < 0.8
if x:
print('hello world!')

Related

Modulo 10 for large Numbers | Checking if a number is in powers of 10 [duplicate]

This question already has answers here:
Mod function fails in python for large numbers
(2 answers)
Closed 4 years ago.
I want to check in Python if a (large integer) value is in powers of 10. Normally I would simply check the modulo 10 of the value. This works fine for values of up to 1.E+22, after that, it returns weird values:
lowInteger = 1.E12
highInteger = 1.E23
print(lowInteger % 10) #as expected returns 0
>>> 0.0
print(highInteger % 10) #returns 2.0 instead of 0.0, 1.E23 returns 3.0, etc
>>> 2.0
The floating point number 1.E23 is not a power of 10. It is the nearest representable number to the power of 10 you wanted. Its actual value is
>>> int(1e23)
99999999999999991611392
If you want exact integers, use ints, not floats. You want 10**23.
>>> 10**23
100000000000000000000000
Also, if you want to check whether a number is a power of 10, x % 10 == 0 is the wrong check anyway, because that's checking whether the number is a multiple of 10.

Write Numeric Manipulation in Python in 1 line [duplicate]

This question already has answers here:
How can I clamp (clip, restrict) a number to some range?
(9 answers)
Closed 4 years ago.
i have a simple problem in Python where i need to return a value that is equal to floor if it is smaller than floor, and return ceiling if the value is larger than ceiling. I'm not sure if there is a simpler way to do so. What i will do is:
def floor_ceil(x):
floor = 0
ceil = 100
if x < floor:
return floor
elif x > ceil:
return ceil
return x
Are there simpler ways to do so? The code looks clunky
You could reuse the built-in max and min:
def floor_ceil(x):
return max(0, min(100, x))

Generating duplicates with weights (python) [duplicate]

This question already has answers here:
A weighted version of random.choice
(28 answers)
Closed 4 years ago.
I have the following list:
priority=['Emergency','High','Normal','Low']
I need to generate a list of 15000 values in the list above, with frequency of each of them being 10%,20%,30%,40%. Can somebody show me how to do it?
Probably the easiest way is to use choice function of numpy.random.
import numpy as np
priority=['Emergency','High','Normal','Low']
b = np.random.choice(priority, 150, replace=True, p=[0.1, 0.2, 0.3, 0.4])
print(b)
Built-in random.choices does the same thing but it is not available <3.6.
You can use random.random(), and assign indexes based on the range of the random number.
In [21]: priority=['Emergency','High','Normal','Low']
In [22]: idx = lambda x: 0 if x < 0.1 else (1 if x < 0.3 else (2 if x < 0.6 else 3))
In [23]: import random
In [24]: [priority[idx(random.random())] for _ in range(15000)]
Out[24]:
['Normal',
'High',
'Emergency',
'Emergency',
'High',
.
.
In the above, I've relied on the order of the elements within your list to generate indexes, such that for 0 to 0.1 it is the first (10%), 0.1 to 0.3 its the second (0.3 - 0.1 will cover 20%), and so on.

Python finding n as 101 instead of 100 [duplicate]

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 6 years ago.
Python loops are finding n as 101 instead of 100, I am getting the average of 5050 as 50 instead of 50.50, What could be the problem? How should I go through it? Here is my function.
def sum_and_average(n):
total = 0
for i in range(1, n+1):
total += i
average = float(total/n)
print "the sum is %d and the average is %f" %(total, average)
sum_and_average(100)
It returns:
the sum is 5050 and the average is 50.000000
Do float(total) / n.
In Python 2 when one of the arguments is float, the calculation will be carried out in float.
But doing float(total/n) won't work, since total/n has already been calculated in integers, and floating the result is already too late.
To get the average you want this:
average = float(total)/n
Some examples:
>>> float(101/2)
50.0
>>> 101/2
50
>>> float(101)/2
50.5

Computing PI in Python 2, how to stop answer truncating [duplicate]

This question already has answers here:
How to define a decimal class holding 1000 digits in python?
(4 answers)
Closed 7 years ago.
please go easy on me, I've been learning Python about a week!
I thought I'd try calculating Pi using the Rumanujan formula. I am confident I was able to code that correctly.
My answer is truncating and I'd like it to be represented with 200 dp. In C I'd use malloc to do this perhaps but I understand that Python doesn't work that way.
The learning point I'd like to take away from this is: Is the truncation caused by the limit of representing a float, and if so is it possible to fix?
Thanks.
import math
from decimal import *
getcontext().prec = 200
def iterate(n):
sum = 0
Decimal(sum)
sum = (math.factorial(4*n))
sum = (sum/math.pow(math.factorial(n), 4))
sum = sum*((26390*n +1103)/math.pow(396, (4*n)))
return sum
ans=0
Decimal(ans)
print "Choose the number of iterations:\n"
itnum = int(raw_input())
for n in range (0, itnum+1):
this_iteration = 0
Decimal(this_iteration)
this_iteration = iterate(n)
ans = ans + this_iteration
ans = ans*(math.pow(8, 0.5)/9801)
ans = 1/ans
print "%.200f" % ans
Your snippet
sum = 0
Decimal(sum)
leaves sum set to the int 0, and computes and throws away a Decimal equivalent. Use, instead, an assignment statement:
sum = Decimal(0)
Next, you'll need to ensure every intermediate result is also converted appropriately to Decimal (and floats by default are not).
Personally, I'd recommend using gmpy2 instead, but then, I'm biased:-).

Categories

Resources