What's the fastest way of getting random value -1 or 1?

Hello. I’m making tree generation system. I did 2 tree grow patterns already, and now I’m making third - for trees like pine. For it I need use function, which will generate -1 or 1 randomly. But what’s the fastest way to achieve it?

I found this way:

(math.random(0, 1) - 0.5) * 2

(10.000.000 usings cost 0.5 s)

Also, before I used

if math.random(0, 1) == 0 then -1 else 1

but this way, 10.000.000 usings cost 0.7 s

So, I start wondering:
Is there any faster ways to get that value?

Note: only values -1 and 1, not including 0

I can’t think of any faster way, even micro optimizations like this are usually not worth it though. A difference of 0.2 ms is pretty okay, but you can probably improve other areas of the code more.

Side note: Timed performance tests are not ideal for comparing different instructions, as it may vary on multiple factors. While it may be quite consistent on one machine, it may still vary. For me I got values between as high as 0.75 from time to time on your most efficient test, while mostly landing in the 0.34 range.

It may be hard to tell exactly how many instructions are being executed by the CPU, but just looking at the code it seems to be one of the simplest possible operations. Randomizing may take some time, but the rest of it (the arithmetic portion) is quick. Either way, improving by an additional millisecond or two probably won’t make or break your game. Instead, as I mentioned before, I recommend you focus your attention elsewhere. Is there a particular reason you want an even faster way than this?

local randtable = {[0]=-1, [1]=1}
local ran = randtable[math.random(0,1)]

What is the convenience - you can do something besides -1 and 1

sadly, this way not faster. It’s 0.65+ s

image
:confused:

Maybe try test my 2 variants on your device?

best, 0.2

(math.random(0, 1) - 0.5) * 2

I even blunted that the selection from the table is longer than the math operations

2 Likes

idek what is happening

image

the results you are getting are somehow slower. I got the same results as Alex with his methods

Not solution. This way you can get zero, while I need only -1 and 1.

I recommend that you use this (math.random(0, 1)-0.5)*2 because I’m not sure you’ll find anything faster and not built-in than math operations

local s = os.clock()
local num = 1664525 * s + 1013904223

for i = 1, 1e6 do
	if num == 0 then
		num = 1664525 * num + 1013904223
	end

	local THERANDOMNUMBER = (bit32.band(num, 1) - 0.5) * 2
	num = bit32.rshift(num, 1)
end

print(os.clock() - s)

local s = os.clock()

for i = 1, 1e6 do
	local THERANDOMNUMBER = (math.random(0, 1) - 0.5) * 2
end

print(os.clock() - s)