0 votes

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

in Engine by (115 points)

2 Answers

+1 vote

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
by (63 points)
+1 vote

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
by (1,018 points)

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.