Share Finding a Maximum Range
Sunday, April 27th, 2008I recently wrote about the Google Chart API but neglected to include a function for finding a maximum range that made sense. The following code can be used to come up with a good range limiter. This is very handy for setting limits on graphs and also for calculating the next level of measurement.
There are two functions doing the work here. The first function, get_max_range() is the one you will call in your code passing in your value as a singular parameter. It will return an integer value that you can use as your delimiter for the maximum value on your graph. The second function is a helper function that is used recursively to determine the base unit of the most significant digit. That value then becomes the exponent of the divisor and multiplier in the ceil() function and the return value.
function get_max_range($num){ // Erik Giberti, 2008 $magnitude = pow(10,get_exponent(abs($num),0)); $new_num = ceil(abs($num)/$magnitude); if($num < 0){ $new_num = $new_num * -1; } return $new_num * $magnitude; } function get_exponent($num, $mag = 0){ // Erik Giberti, 2008 if($num/10 > 1){ return get_exponent($num/10, $mag+1); } else { return $mag; } } |
Examples:
As you’ll see it works equally well with positive and negative numbers.
get_max_range(0.1) = 1 get_max_range(1.2) = 2 get_max_range(23.45) = 30 get_max_range(364)= 400 get_max_range(4567) = 5000 get_max_range(-59136789) = -60000000
Limitations:
1. While this works well for both positive and negative numbers, it doesn’t work well for very small numbers. For example 0.012 will still return a maximum scale of 1. If someone would like to expand on this work, please feel free and I’ll post the changes here.
2. Very large numbers only consider the most significant digit. The of course could be changed by altering the base_exponent value to better suit your datasets. I find this general value works well for graphing which is what this was intended for anyway.
License:
This code is released to you for use under the GPL.