It seems like a no brainer but I am having trouble to get this solved:
I would like to calculate a level based on given experience points (exp). Therefore I use the cube root formula and round down to the next whole number. The next level is reached when exp exactly reaches level^3
. The number of levels is unlimited, so I would avoid having a pre-calculated lookup table.
When I use the standard php math
floor( pow( 10648, 1/3))
It returns 21 instead of 22. This is wrong since 21^3 gives 92161. The reason is that due to limited floating point precision pow(10648, 1/3) returns not exactly 22, instead it returns 21.9993112732. You can check it out with the following snippet:
$lvl = pow( 10647, (float) 1 / 3);
print number_format( $lvl, 10);
This is my workaround. But I am not sure if this is bulletproof:
public static function getLevel($exp) {
$lvl = floor(pow($exp, (float) 1 / 3)); // calculate the level
if (pow($lvl + 1, 3) == $exp) { // make check
$lvl++; // correct
}
return $lvl;
}
Also it looks a bit fragile when it comes to the check. So the question remains: Is there a reliable, efficient and bulletproof way of calculating cube root (of positive numbers).
Thanks.