I apologize if the title is not clear, but I couldn't explain it succinctly.
Given a vector of concentrations, I would like to round the maximum value to the next order of magnitude (i.e., 345 to 1000). Also, I would like to round the minimum value to the lower order of magnitude (i.e., 3.2 to 1). These concentrations may also be below 1 so for example 0.034 would need to be rounded to 0.01.
Any ideas?
To round a number to its nearest order of magnitude, one rounds its logarithm to the nearest integer. Thus 4000000, which has a logarithm (in base 10) of 6.602, has 7 as its nearest order of magnitude, because "nearest" implies rounding rather than truncation.
Order of magnitude refers to the class of scale of any numerical value in which each class contains values of a fixed ratio to the class before it. On a logarithmic scale -- such as base 10, the most common numeration scheme worldwide -- an increase of one order of magnitude is the same as multiplying a quantity by 10.
The "order of magnitude" of a number is a rough estimate of how big it is. One order of magnitude is a factor of ten. Two orders of magnitude is: 10 * 10 = a factor of 100. Five orders of magnitude is: 10 * 10 * 10 * 10 * 10 = a factor of 100,000.
Python abs() The abs() function returns the absolute value of the given number. If the number is a complex number, abs() returns its magnitude.
Here's a simple function that does what you're after:
log10_ceiling <- function(x) {
10^(ceiling(log10(x)))
}
log10_ceiling(c(345, 3.2, 0.034))
# [1] 1000.0 10.0 0.1
I'm not sure about R, but this is a simple process to describe algorithmically.
Take the base 10 logarithm of the number, and apply a ceiling or floor to the result. Raise 10 to that power. Done.
You need a special case for 0 because you can't take a logarithm of 0.
In case someone is interested, the following is Ostermiller's solution translated to Python:
def roundUpToNearestMagnitude(n):
if n == 0:
return 1
negative = n < 0
log = np.log10(abs(n))
if log > 0:
decimalPlaces = np.ceil(log)
else:
decimalPlaces = np.floor(log) + 1
rounded = np.power(10, decimalPlaces)
if negative:
return -rounded
else:
return rounded
def test_roundUpToNearestMagnitude():
assert(100 == roundUpToNearestMagnitude(50))
assert(10 == roundUpToNearestMagnitude(5))
assert(1 == roundUpToNearestMagnitude(0.5))
assert(.1 == roundUpToNearestMagnitude(0.05))
assert(.01 == roundUpToNearestMagnitude(0.005))
assert(-100 == roundUpToNearestMagnitude(-50))
assert(-10 == roundUpToNearestMagnitude(-5))
assert(-1 == roundUpToNearestMagnitude(-0.5))
assert(-.1 == roundUpToNearestMagnitude(-0.05))
assert(-.01 == roundUpToNearestMagnitude(-0.005))
assert(1 == roundUpToNearestMagnitude(0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With