Generate float values between -1 and 1

2

I am trying to generate float values between -1 and 1 to test if they are within the defined limits in order to create a vector with the amount of data I want only that I am only able to generate% between 0 and 1 through the function float in the function that I defined, I know there is the random() function but I am not able to enter it in the uniform() function, 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 I run 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
    
asked by anonymous 23.11.2018 / 10:01

2 answers

5

If you can already generate the positives, I will not go into the merit if it is right or not, it is pure mathematics, instead of generating from 0 to 1 you generate from 0 to 2, there subtract 1, 1. I would do so, but it seems that idiomatically the recommendation is to use the method uniform() :

import random

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

See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .

    
23.11.2018 / 11:30
6

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 floating point random number within the range [0.0, 1.0]. Recalling that the parenthesis by limiting the 1.0 in the range indicates that this value will not be included.

While

  

random.uniform(a, b)

     

Return to random floating point number N such that a

23.11.2018 / 11:38