2
votes

I was wondering why I had invalid data for a script, then I tried to test math.random since it seemed to be coming from it's return values. This is what I got from the Lua console :

> return  math.random(0.8, 1.2);
0.8
> return  math.random(0.8, 1.2);
0.8
> return  math.random(0.8, 1.2);
0.8
> return  math.random(0.8, 1.2);
1.8
> return  math.random(0.8, 1.2);
0.8
> return  math.random(0.8, 1.2);
1.8
> return  math.random(0.8, 1.2);
0.8
> return  math.random(0.8, 1.2);
1.8
> return  math.random(0.8, 1.2);
0.8

I am a little confused about the results I'm getting. Someone can clarify?

2
To add to what Marc B says, and in order to do what you want to do, you can easily rectify it by doing: return (math.random(8,12)/10), which will return 0.8 to 1.2. - Josh
@Josh actually, what I've been doing is this : 0.8 + (math.radnom() * 0.4). This way, I have more precision variation. - Yanick Rochon

2 Answers

7
votes

http://lua-users.org/wiki/MathLibraryTutorial

upper and lower must be integer. In other case Lua casts upper into an integer, sometimes giving math.floor(upper) and others math.ceil(upper), with unexpected results (the same for lower).

1
votes

Will said Yanick Rochon

upper and lower must be integer. In other case Lua casts upper into an integer, sometimes giving math.floor(upper) and others math.ceil(upper), with unexpected results (the same for lower).

therefore:

return math.random(0.8, 1.2); 0.8

The Documentation Reference said:

math.random ([m [, n]]) This function is an interface to the simple pseudo-random generator function rand provided by ANSI C. (No guarantees can be given for its statistical properties.) When called without arguments, returns a uniform pseudo-random real number in the range [0,1). When called with an integer number m, math.random returns a uniform pseudo-random integer in the range [1, m]. When called with two integer numbers m and n, math.random returns a uniform pseudo-random integer in the range [m, n].

font: http://goo.gl/eJvLup