Generate float values between -1 and 1

Asked

Viewed 909 times

4

I’m trying to generate values float between -1 and 1 to test if these are within the defined limits to create a vector with the amount of data that only means that I am only able to generate values float between 0 and 1 through the function random() in the function I have defined, I know there is a function uniform() but I’m not getting it into function criavetor(dados), my code is as follows::

from random import random # para gerar os nums aleatorios com ponto flutuante

"""
Valores de Teste 
"""
"""
Função de criação de vetor de valores aleatórios entre 0 e 1
"""
"""
Limites 
"""
limite_max=0.8# limite máximo
limite_min=-0.8# limite mínimo

"""
Gerar valores para teste 
Função de criação de vetor de valores aleatórios entre 0 e 1
"""
def criavetor(dados):
    val=[]
    for i in range(dados): # fazer isto (N) vezes
        val.append(random()) # adiciona o numero seguinte gerado aleatoriamente entre 0 e 1 ao vetor vec  
    return val
"""
# Inserção da quantidade de valores a gerar
"""
dados = int(input('Quantidade de valores a serem gerados:'))
val = criavetor(dados)# a variável global val é igual aos dados da função criavetor(dados)
"""
Comparação entre os valores gerados e os limites máximo e mínimos
se os valores estão dentro dos limites definidos estão OK, se estiverem fora desses limites estão NOT OK
"""
for x in val:
    print("\n")
    print("O valor de x é: ", round(x, 3))    
    if x >= limite_min and x <= limite_max: 
        print("OK")
    else:
        print("NOT OK")

the output when executing the code is as follows:

Quantidade de valores a serem gerados:5


O valor de x é:  0.522
OK


O valor de x é:  0.973
NOT OK


O valor de x é:  0.122
OK


O valor de x é:  0.218
OK


O valor de x é:  0.74
OK
  • 1

    In the documentation it says: "Return the next Random floating point number in the range [0.0, 1.0)". Try using another module function.

2 answers

7


If you can already generate the positives, I won’t enter into the merit if you’re right or not, it’s pure mathematics, instead of generating from 0 to 1 you generate from 0 to 2, then subtract from 1, then you get from -1 to 1. I would do so, but it seems that idiomatically the recommendation is the use of the method uniform():

import random

print([random.uniform(-1, 1) for _ in range(20)])

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • 2

    The Python Random module provides several functions to generate numbers and other random options as needed. In this case, the distribution random.uniform accepts the smaller and larger limits for a numeric range. In almost all other languages, random number generation is restricted to values between 0 and 1, and the programmer has to transform the number later - but it is one of the "batteries included" factors responsible for Python’s success. (Random.Uniform is the least, but the amenities random.choice and random.shuffle really make a difference )

  • And does it have any real and clear advantage? Or just because it already has and gives in the same?

  • 1

    functional advantage does not - but it is one of the characteristics of language: lets you worry about your problem - the obvious and small things you do not have to keep redoing. In any code revision the strong suggestion would be to switch to the Random.uniform. In my view, a very cool answer here would have to explain "how it is done in other languages" and "Python already does this with random.uniform )

  • @jsbueno Ready then

7

Just read the documentation of what you are using.

random.random()

Return the next Random floating point number in the range [0.0, 1.0).

Translating, returns the next random number with floating point within the range [0.0, 1.0). Remembering that the parenthesis limiting the 1.0 in the range indicates that this value will not be included.

While

random.uniform(a, b)

Return a Random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

Translating, returns a random number with floating point N so that a <= N <= b for a < b and b <= N <= a for b < a. Note that, unlike the random, the ends of the range are included by the uniform, can return -1.0 or 1.0.

Read the documentation for more details on rounding issues when using this function.

Browser other questions tagged

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