how to generate 10000 random no. in a range 30,40 [duplicate] - python

This question already has answers here:
How to get a random number between a float range?
(6 answers)
Closed 6 days ago.
I have issue i want to generate 10000 random float no's in a given range, I cannot use random module because it will always go out of my range
x=random.randrange(30.000000,40.000000,10000)
i tried this
and i'm exepcting 10,000 random float no. b/w them

You could use random.uniform like:
import random
x = [random.uniform(30.0, 40.0) for i in range(10000)]
Alternatively, you could use numpy like:
import numpy as np
x = np.random.uniform(30.0, 40.0, 10000)
NB:
The second option would give you an ndarray, which is normally fine, but if your program requires you to have a list instead, you can just do this instead:
import numpy as np
x = np.random.uniform(30.0, 40.0, 10000).tolist()

You can try to use random.uniform:
for i in range(10000):
random.uniform(30.0, 40.0)
I see you're trying to assign the float values to x, you can do so with:
x = []
for i in range(10000):
x.append(random.uniform(30.0, 40.0))

Use numpy.random.uniform:
x = np.random.uniform(30.000000, 40.000000, 10000)
array([35.8284953 , 36.31252488, 37.0409413 , ..., 39.07939188,
33.76935076, 31.11123249])

Related

How to calculate the Mean Median Mode and Range for datas from Input Python

I am trying to Calculate the mean, median, mode and range for sets of data in Python, and to Interpret these statistics in the context of data and how to describe and interpret data displays using median, mean and range.
My Code so far is:
from statistics import median
from statistics import mean
from statistics import mode
from math import isnan
from itertools import filterfalse
title = input('Definition of data set: ')
data = (float(input("Enter a list element separated by space: "))
xy = mean(data)
print(x)
y = statistics.mode(data)
print(y)
z = statistics.median(data)
print(z)
But the code doesn't work...
and i believe its completely wrong.
Could anyone help by 24th of October???????
The way you are defining 'data' is wrong. You can try the code below. I only change the 'data' variable.
from statistics import median
from statistics import mean
from statistics import mode
from math import isnan
from itertools import filterfalse
title = input('Definition of data set: ')
# Input list of element wit space and convert it to list
data = list(map(float, input('Enter the list of element: ').split()))
print(data)
x = mean(data)
print(x)
y = mode(data)
print(y)
z = median(data)
print(z)
Looks like you want input as a list of floating point numbers separated by space. You need to convert that into a list of floats which you can then pass to each of the statistical functions:
from statistics import mean, median, mode
data = input('Input values separated by space: ')
list_of_values = list(map(float, data.split()))
for func in mean, median, mode:
print(f'{func.__name__}={func(list_of_values)}')
print(f'range={min(list_of_values)}-{max(list_of_values)}')
Example:
Input values separated by space: 3 2 2.5 3 9 7.1
mean=4.433333333333334
median=3.0
mode=3.0
range=2.0-9.0

How would I generate a random sequence of numbers without going accidently going over the same numbers? [duplicate]

This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Generate 'n' unique random numbers within a range [duplicate]
(4 answers)
Closed last year.
This is probably a duplicate of something, but oh well.
I'm trying to create a random number generator that goes over all 7 digit numbers (0000001 - 9999999) but I'm having issues thinking how I'd code such a mechanism; would anyone know any libraries or functions that may help here?
Edit: Big thanks to Kelly Bundy and Alexpdev for helping me understand how I can code this script
In addition to the answers linked in the original post comment section, you can also use numpy to generate an array of x length and randomise the order:
import numpy as np
x = 10000000
a = np.arange(x)
np.random.shuffle(a)
print(a)
This is the example straight from numpy's website
np.arange(x) creates an array from 0 to x-1, stepped at 1. Numpy can then shuffle your array inplace.
Beyond 9 digits, this answer becomes unfeasible due to memory limitations, in which case you'd simply be better off using a generator or RNG function.
If you want to format your number as a string and fill it with padding zeros, eg 0000020 instead of 20, you can do:
str(a[idx]).zfill(7)
Using the random module that comes with python you can use the randint function to get a random integer in the range of it's arguments.
Then cast the result to a str and pad it with "0"s for the desired output.
import random
def get_random_sequence():
num = random.randint(0,9999999)
return str(num).rjust(7,"0")

The values of a vector in python are shown as nan value [duplicate]

This question already has answers here:
How can I take the square root of -1 using python?
(6 answers)
Closed 1 year ago.
I have a vector y with size, for example, (1,64). I create a vector in python as follows:
vec = np.pi * np.sqrt(-1) * range(len(y))
I get the output values of the vector vec are all nan or the majority of them are nan.
What i'm trying to accomplish with range(len(y)) in the above code, is to create a vector including 0, 2, 3, ... with the length of y.
How can I solve that issue, please?
You're getting nan because you're using the square root of -1, as for range(len(y)) it creates a range object with items from 0 to len(y) - 1, however you can't use mathematical operations on it as is, you need to pass it to numpy.array or have a numpy object in the expression , (this is satisfied by np.sqrt function), another way would be np.array(range(len(y)))
a working example:
vec = 2*np.pi*np.sqrt(1)*0.5*range(len(y))
if you'd like to use imaginary units you need to express the number as an complex number use the expression i+jk
so your code would be ( 2 *0.5 removed because it's redundant)
vec = np.pi*np.sqrt(-1 + 0j)*np.array(range(len(y)))
you need complex class like below:
import cmath
vec = 2*np.pi * cmath.sqrt(-1)*0.5* np.array(range(len(y)))
vec
output:
array([0.+0.j , 0.+3.14159265j, 0.+6.28318531j, 0.+9.42477796j])

How to generate a random number to 2dp [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
I am trying to work on a random number generator which produces a random number which is to 2dp regardless of whether it needs to be. eg. 2.10 is 2.10 not 2.1, 3 = 3.00
import random
temp_var_4_int = random.randint(2,5) + round(random.random(),2)
print (temp_var_4_int)
It should randomize a number between 2 and 5 and then add a decimal to it which is rounded to 2 decimal places but I keep getting answers such as:
1.2700000000000002 instead of 1.27
I'm not sure why it's throwing this anomaly at me.
assuming you want your numbers in [0, 10] you could just do this:
from random import uniform
r = round(uniform(0, 10), 2)
print(f"{r:3.2f}")
if r = 2.1 the format string will represent it as "2.10"; but for all mathematical purposes the trailing zero has no effect.
import random
print("Printing random float number with two decimal places is ",
round(random.random(), 2))
print("Random float number between 2.5 and 22.5 with two decimal places is ",
round(random.uniform(2.5,22.5), 2))
You can format the float with two digits like:
import random
temp_var_4_int = random.randint(2,5) + round(random.random(),2)
temp_var_4_int = '%.2f' % (temp_var_4_int)
print(temp_var_4_int)
According to this Q&A
(0.1+.02)
will return
0.12000000000000001
and
'%.2f' % (0.1+.02)
will return
'0.12'
Try it if you please and let me know, is another example of the same issue
Try to use string formatting:
from random import randint, random
temp_var_4_int = round(randint(2,5) + random(), 2)
print(temp_var_4_int)
print(f"{temp_var_4_int:.2f}")
That would output something like:
2.1
2.10
Please note that f-strings works on Python 3.6+

How to generate random samples from a population in Python?

I'm trying to address this question:
Generate 1,000 random samples of size 50 from population. Calculate the mean of each of these samples (so you should have 1,000 means) and put them in a list norm_samples_50.
My guess is I have to use the randn function, but I can't quite guess on how to form the syntax based on the question above. I've done the research and can't find an answer that fits.
A very efficient solution using Numpy.
import numpy
sample_list = []
for i in range(50): # 50 times - we generate a 1000 of 0-1000random -
rand_list = numpy.random.randint(0,1000, 1000)
# generates a list of 1000 elements with values 0-1000
sample_list.append(sum(rand_list)/50) # sum all elements
Python one-liner
from numpy.random import randint
sample_list = [sum(randint(0,1000,1000))/50 for _ in range(50)]
Why use Numpy? It is very efficient and very accurate (decimal). This library is made just for these types of computations and numbers. Using random from the standard lib is fine but not nearly as speedy or reliable.
Is this what you wanted?
import random
# Creating a population replace with your own:
population = [random.randint(0, 1000) for x in range(1000)]
# Creating the list to store all the means of each sample:
means = []
for x in range(1000):
# Creating a random sample of the population with size 50:
sample = random.sample(population,50)
# Getting the sum of values in the sample then dividing by 50:
mean = sum(sample)/50
# Adding this mean to the list of means
means.append(mean)

Categories