0

This may sound easy but i am weak in math. I would like to get the value of x that must follow the condition

  • The randomised variable x must be larger than radius

  • The randomised variable x must be less than (innerWidth - radius)

    var x = Math.random() * innerWidth ;

    var radius = 20;

Can someone pls help me. I am sure it is more of a mathematics than my coding skills.

[enter image description here][1]

[1]Image Stuck at the screen : https://i.stack.imgur.com/Ib1km.png

  • See [this post](https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript). It details how to generate a random number *inside a specified range*, which seems like what you're trying to do. In your case, `innerWidth - radius` would be the upper bound and `radius` would be the lower bound. – AbeMonk Jul 20 '23 at 02:35

1 Answers1

0

Math.random() gives you a random value between 0 and 1.

So, Math.random() * n gives you a random value between 0 and n.

Since you need random values between radius and innerWidth - radius, we'll get the random values between 0 and innerWidth - radius * 2 and then add radius to it, which will give us random values between radius and innerWidth - radius. Right?

So, what you need is:

var x = Math.random() * (innerWidth - 2 * radius) + radius;
technophyle
  • 7,972
  • 6
  • 29
  • 50