2

I'm new at LUA and I need a help with code in using function math.random(...). The problem is if I need to generate integer values I just use

math.random(-1, 1) -- This is gonna be -1, 0 or 1. Profit.

But if I need non-integers between -1 and 0?

math.random(-1.0, 1.0) -- Still -1, 0 or 1. No profit.

I tried using this: -1.01, 1.01 but it is not gonna generate a number between values exactly I need.

How do I generate non-integer value between 1 and 0?

2
  • I think there's an error in your question, math.random() generates random values between 0 and 1. Commented Nov 23, 2019 at 23:02
  • @poorandunlucky yes I think I just forgot it, but I meant that I need to generate non-integer values for example between x and y variables, not just 1 and 0. Commented Nov 24, 2019 at 13:12

2 Answers 2

6

Without arguments, math.random returns a floating-point number between 0 and 1. You can get other ranges by multiplying and adding:

math.random() * 2 - 1

Or more generally:

math.random() * (maximum - minimum) + minimum
Sign up to request clarification or add additional context in comments.

3 Comments

Hey, thanks for this! Is there a way I could limit fractions from the value I get with math.random() * (maximum - minimum) + minimum? For example if I use math.random(-1.1, 1.1) I'm getting only tenth from the value (x point y) or if I use math.random(-1.11, 1.11) I'm going to get the hundred from the value (x point yz). But using this I'm getting a very big fraction.
Do you just need to round off the output, or do you really need a number that's right at a hundredth? Either way, that sounds like it should be a separate question.
I guess you're right. Im just curious because the original way worked like this so it would be very useful.
1

You could also do something like math.random(-1, 1) + ( math.random(1, 99) / 100 ). Hopefully this helps a bit. math.random will only get whole numbers and integers. It won't return floats unfortunately.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.