Randi() function is not functioning well

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Dava

I found a problem with godot’s randi() function.
When I write:var num = randi()%20 +10
its supposed to return integer values between 20 and 10,
but instead it returns values between 30

:bust_in_silhouette: Reply From: EIREXE

By doing randi()%20 what you are doing is limiting it to 20, the problem is that if you get for example 15 and then add 10 to it it will be 25.

So the best way to do this would probably be:

var num = randi() % 10 + 10
:bust_in_silhouette: Reply From: Bartosz

Here how you use randi

Docs says that randi() returns value between 0 and N (where N is smaller than 2^32 -1).

reminder operator a % b return c that is between 0 and b

so var r = randi() % 20 is number between 0 and 20

if you add 10 to it - var r = (randi() % 20) + 10 it becomes number between 10 and 30 ( 0 + 10 and 20 + 10)

To get random integer from some range you could use this function

func random_int(min_value,max_value, inclusive_range = false):
  if inclusive_range:
    max_value += 1
  var range_size = max_value - min_value
	return (randi() % range_size) + min_value

var r = randi() % 20 is number between 0 and 19, not 0 and 20. Since those are the only possible remainders.

Rodrigo Matos | 2020-01-20 01:43