Weird Math

Trying to create a 3 digit random number, from 50 to 175 (to emulate a HR value for testing in Eclipse.

Anyway, check this out. Weird. The decimal portion of "b" should simply be the last 3 digits of the integer portion of "a". It never is. Any ideas?

var a = Math.rand().toFloat();
System.println("A: " + a);
var b = a / 1000f;
System.println("B: " + b);
var c = b.toNumber();
System.println("C: " + c);
var d = ((b - c.toFloat()) * 1000f).toNumber()/8+50;
System.println("D: " + d + "\n");


=========================================
A: 1796216192.000000
B: 1796216.250000
C: 1796216
D: 81

A: 1283134080.000000
B: 1283134.125000
C: 1283134
D: 65

A: 1900381440.000000
B: 1900381.500000
C: 1900381
D: 112
  • Actually, that's what happens with floats in general. Recall that in MC,

    Floats - 32-bit floating point numbers

    They are only 32 bits, and can't actually store every value. Doubles are better, and in MC are

    Doubles – 64-bit floating point numbers

    But, before you change things, if you want a random number between 50 and 175, you could just do this:

    randValue = 50+(Math.rand()%126);

    It will be a value between 50+0 and 50+125
  • Thank you!!

    Thanks for the reminder and the better solution to a RANDBETWEEN!

    Actually, that's what happens with floats in general. Recall that in MC,

    Floats - 32-bit floating point numbers

    They are only 32 bits, and can't actually store every value. Doubles are better, and in MC are

    Doubles – 64-bit floating point numbers

    But, before you change things, if you want a random number between 50 and 175, you could just do this:

    randValue = 50+(Math.rand()%126);

    It will be a value between 50+0 and 50+125