Manipulating Python Lists with a mathematical formula

Asked

Viewed 93 times

0

I have to make a certain calculation with real numbers generated randomly in Pyton. In my case, there will be 10 randomly generated numbers, and after that, I need each number on my list to be entered in my formula for the calculation to be carried out. The formula is: minimum + (maximum - minimum)* x where x is every randomly generated number on my list

so far I’ve done so:

minimo = 50
maximo = 130

numrandomicos = [random.uniform(0,1) for r in range(10)]
print(numrandomicos)

  • Am I already looped? If so, just make a loop that runs through your list applying the desired formula on each value.

  • I used a loop with for, it looked like this: for numero in numrandomicos: numeros = minimo+(maximo-minimo)*numrandomicos print(numeros)

  • And that’s not what you need to do?

2 answers

2

You have a sequence of values and want to generate another value from them. This is a 1:1 ratio, that is, for each input value you generate an output value. This process is called mapping and can be implemented in Python with the function map:

resultado = map(lambda x: minimo + (maximo - minimo)*x, numrandomicos)

The expression lambda in this case will implement the function you want to apply on the values.

0

I decided as follows:

for numero in range(10):
    numrandomicos = random.uniform(0,1)
    numero = minimo+(maximo-minimo)*numrandomicos
    print(numero)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.