dcvl
dcvl

Reputation: 595

How to make python random.random() incorporate negatives

I'm trying to generate a pair of random numbers between -1 and 1.

I can make it go negative OR positive...but not generate a random number for x and y that may turn out negative as well as positive. Below is what I have (it's a dart throw simulation game from a website). randx and randy are where the random number generation is happening to be used as the coordinates.

import turtle
import math
import random

def main():

    fred = turtle.Turtle()
    fred.up()

    wn = turtle.Screen()
    wn.setworldcoordinates(-1,-1,1,1)

    numdarts = 10
    for i in range(numdarts):
        randx = random.random()
        randy = random.random()

        x = randx
        y = randy

        fred.goto(x,y)
        fred.stamp()

    wn.exitonclick()

main()

Upvotes: 2

Views: 1123

Answers (3)

dotancohen
dotancohen

Reputation: 31491

Since random.random() will give you a float between [0.0-1.0), you can extend that range to [0.0-2.0) by multiplying by 2. You can then move that range to [-1.0-1.0) by subtracting 1:

import random

randx = random.random()*2.0 - 1.0

Upvotes: 2

Jobs
Jobs

Reputation: 3377

You can generate random numbers from 0 to 2 using random.random(), then shift all of your results by 1, to -1 to 1.

Upvotes: 0

user14717
user14717

Reputation: 5161

I assume you want a floating point number. In that case, use

x = random.uniform(-1,1)

Upvotes: 8

Related Questions