Eleonara
Eleonara

Reputation: 35

AS3: can't figure out Math.random

I'm very bad at math, so i can't figure out why this isn't working. It should calculate a random number between 0 and 360.

var minDegree:int = 0
var maxDegree:int = 360

function randomDegree (minDegree:Number, maxDegree:Number):Number 
{
    return (Math.random() * (maxDegree - minDegree + minDegree));
    trace(randomDegree)
}

Upvotes: 1

Views: 122

Answers (2)

Xenophage
Xenophage

Reputation: 85

You were very close, move the closing parenthesis over a little. Multiplying the difference between max and min, then adding min back on to bring the value back into the proper range. I find it easy to try some examples using a simple calculator and seeing if the results make sense.

var minDegree:int = 0
var maxDegree:int = 360

function randomDegree (minDegree:Number, maxDegree:Number):Number 
{
    return Math.min(maxDegree, Math.random() * (maxDegree - minDegree) + minDegree + .01);
}

trace(randomDegree(minDegree, maxDegree));

Upvotes: 0

Andrey Popov
Andrey Popov

Reputation: 7510

I assume you actually want integers, right? This is the actual code:

private function randRange(minNum:Number, maxNum:Number):Number 
{
    return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}

I'm posting it because @Xenophage's answer is not correct. And it's not correct because of the fact that Math.random Returns a pseudo-random number n, where 0 <= n < 1. (reference). What this means is that if you pass 0 as minimum and 360 as maximum, the biggest number you can get is 359 because:

(Math.random() * (maxDegree - minDegree) + minDegree);
(0.99999 * (360 - 0) + 0) = 359

So the upper solution would work better :) If you are not looking for an integer - let me know.

Edit: I've made the random to return more precise number, as if it was simply 0.99 it would calculate to 354 instead of 359. Either ways won't go up to 360. And yes, I know you need degrees, so 0 is similar to 360 if you are not doing some precise calculations, but I had to mention it as it's a Math.random problem, not a degrees problem.

Upvotes: 1

Related Questions