0

I have two numbers wich can change, like x1 and x2. Then I also have an other number what is random but always between x1 and x2, like z. What I want to do is change z to the nearest x.

Sooo if I give you guys an example:

Input:

x1 = 12.24
x2 = 346.92
z = 274.45

Output:

z = 346.92

z is now 346.92 because that is the nearest number for z. This is what I am trying to do in Javascript. I thought there was no command for and you have to do it with just some math. I really have no idea how to do that... But there are you!

Thnx for all your help!

Thomas Pereira
  • 239
  • 1
  • 4
  • 18

6 Answers6

0

How about this?

z = (Math.abs(z-x1)<Math.abs(z-x2))?x1:x2;

If you're sure x1 < x2, then:

z = ( (z-x1) < (x2-z) ) ? x1 : x2;
lpg
  • 4,897
  • 1
  • 16
  • 16
0

Here is a working jsFiddle With Math.abs(z - x1) and Math.abs(z - x2) you get the number between both values. Then you check if the first difference is bigger than the second.

x1 = 12.24;
x2 = 346.92;
z = Math.floor((Math.random() * 346) + 1);
z_ = z;
if (Math.abs (z - x1) < Math.abs (z - x2)){
  z = x1;
}     
else{
  z = x2
}
alert(z_ + " is closer to : "+ z);

Edit : Added a random number every time you run so you can see exactly how it works

Romain Derie
  • 516
  • 7
  • 17
0
z = Math.round((z - x1) / (x2 - x1)) * (x2 - x1) + x1;

Whether x1 is greater than x2 or vice versa, this will consistently move z to the closer of the two.

How does it work?

(z - x1) / (x2 - x1)

Find the difference between z and x1 as a ratio to the difference between the two extrema.

Math.round((z - x1) / (x2 - x1))

Choose an extreme (1 or 0) based on proximity.

Math.round((z - x1) / (x2 - x1)) * (x2 - x1)

Multiple that extreme (1 or 0) by the difference between the two extrema.

Math.round((z - x1) / (x2 - x1)) * (x2 - x1) + x1;

Add the difference to x1, guaranteeing that the result is equivalent to either x1 or x2.

Paul Rowe
  • 778
  • 3
  • 10
0

Try:

z = (Math.abs(x1-z)>(Math.abs(x2-z)) ? x2 : x1);
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

Just calculate the difference by substracting Z from x1, and x2:

if( (z - x1) < (x2 - z)){
  z = x1;
}else{
  z= h2;
}

If the values may get negative .. use Math.abs(z-x1) , Math.abs(x2-z) to get the ABSOLUTE value.

d.raev
  • 9,216
  • 8
  • 58
  • 79
-1

If z is random and evenly distributed:

z = Math.random() > 0.5 : x1 ? x2;
Chris Charles
  • 4,406
  • 17
  • 31