{{ message }}

Instantly share code, notes, and snippets.

# leptos-null/temperature_scaling.md

Last active Dec 23, 2019
How to scale temperature and other measurements

## Temperature Scaling

What’s it mean if the temperature is going to be 30% warmer or 30% cooler?

### Distance Scaling

Let’s take something that we know works: distances. If I have a distance that’s 2 meters, 30% more is (`x=2, s=0.3; x*(1+s)`) 2.6 meters, and 30% less is (`x=2, s=-0.3; x*(1+s)`) 1.4 meters. Covert these three values to feet, you get `6.56`, `8.53`, and `4.59` respectively. If we plug these numbers back into our scaling equation: more is (`x=6.56, s=0.3; x*(1+s)`) 8.528 feet, and less is (`x=6.56, s=-0.3; x*(1+s)`) 4.592 feet. These values are slightly off due to rounding.

### Fixing Temperature

The problem with temperature is that it’s not zero-based. A value some incremental amount warmer than 5 degrees Fahrenheit is still cold. We need to “normalize” temperature. To do that, we have to find a value such that anything warmer feels warmer, and anything cooler feels cooler. We’re going to use 22°C (72°F) for this value.

Our abstract equation looks like this: `(temperature - normalize)*(1 + scale) + normalize` where `normalize` is the temperature discussed in the above paragraph. For Celsius this will be `(x-22)*(1+s) + 22` and for Fahrenheit `(x-72)*(1+s) + 72`.

We’ll take a temperature of 25 Centigrade, 30% more is (`x=25, s=0.3; (x-22)*(1+s) + 22`) 25.9 Centigrade, and 30% less is (`x=25, s=-0.3; (x-22)*(1+s) + 22`) 24.1 Centigrade. Covert these three values to Fahrenheit, you get `77`, `78.62`, and `75.38` respectively. If we plug these numbers back into our scaling equation: more is (`x=77, s=0.3; (x-72)*(1+s) + 72`) 78.5 Fahrenheit, and less is (`x=77, s=-0.3; (x-72)*(1+s) + 72`) 75.5 Fahrenheit. These values are slightly off due to rounding.

### Dealing with a negative coefficient

With normal scales (e.g. distance, time) or abnormal scales (e.g. temperature), the equations I wrote above don’t work correctly when the starting value is negative (e.g. -4 meters). For these cases, the scale needs to go in the other direction.

We can write a general function, with a `normalize` value such that `normalize` is a point that fits our earlier criteria: a change in sign correlates a logical change in meaning (e.g. distance from the start line of a race is negative before the line, and positive after the line).

```def scale_unit(value, scale, normalize = 0):
x = value - normalize
s = 1
if (x < 0):
s -= scale
else:
s += scale
return x*s + normalize```

We can try this out with negative distances: `scale_unit(-4, 0.5)` returns -2 ("50% more than -4 is -2"), seems reasonable.

Let’s try some temperatures: `scale_unit(50, 0.5, 72)` returns 61 ("50% warmer than 50 degrees is 61"), again seems reasonable. `scale_unit(70, -0.6, 72)` returns 68.8, which continues to make sense.