Home > Software design >  adding randomly generated values in increasing order
adding randomly generated values in increasing order

Time:06-01

I want to add the randomly generated values in increasing order instead of fixed 0.2 and 0.5 value inside if else statement.How to do that can anybody guide me? Thanks in advance.

My code is

N=10
dta=[]
x=0.0
for i in range(N):
    dta.append(x)

    if(i<5):
        x=x 0.2  #here instead of 0.2 randomly generated data in range 0.1 to 0.2
                 #should be added( example it may be 0.15,0.16....)
    else:
        x=x 0.5  #here instead of 0.5 randomly generated data in range 0.3 to 0.5
                 #should be added
print(dta)  

CodePudding user response:

This should do it:

import random
N=10
dta=[]
x=0.0
for i in range(N):
    dta.append(x)

    if(i<5):
        x  = random.uniform(0.1, 0.2)
    else:
        x  = random.uniform(0.3, 0.5)
print(dta)

Sample Output:

[0.0, 0.13515152101736566, 0.2866133692895604, 0.4608222800319004, 0.6003500994767033, 0.7898596366391699, 1.2677308143972574, 1.571917695358207, 1.8899333979603337, 2.2967764098732637]

CodePudding user response:

You can use random.uniform:

from random import uniform

dta = [uniform(0.1, 0.2) if i < 5 else uniform(0.3, 0.5) for i in range(10)]

print(dta)
# [0.12400524804802719, 0.17671238221121432, 0.18568790912166208, 0.19944514236086913, 0.1845712112690111, 0.38281919616060733, 0.4653867578531521, 0.41298373391784765, 0.3010598185832497, 0.40519599032549175]
  • Related