Simon Arnold - 2 months ago 10

Javascript Question

I have a value between 0 and 1, but I need to map this value on a range of 0 to 0.5 to 0.

For exemple 0.4 would give 0.4, but 0.8 would also give 0.2.

0.1 = 0.1,

0.2 = 0.2,

0.3 = 0.3,

0.4 = 0.4,

0.5 = 0.5,

0.6 = 0.4,

0.7 = 0.3,

0.8 = 0.2,

0.9 = 0.1

How can I achieve this?

Answer

If its greater than 0.5, subtract it from 1. `1 - 0.9 = 0.1`

To get rid of the conditional, use `Math.Min(x, 1 - x)`

. This works because:

0.1 = 0.1,

0.2 = 0.2,

0.3 = 0.3,

0.4 = 0.4,

0.5 = 0.5,

0.6 = 0.4,

0.7 = 0.3,

0.8 = 0.2,

0.9 = 0.1

Notice that:

- the list is mirrored from [0,1] around 0.5
- there are two numbers on each line, and every line adds to 1.

That's why the Math.Min works. Input, output, its all the same. You just want the minimum of the two numbers. So say you start out with `0.1`

. That is mirrored with `0.9`

, and *both* of these values map back to `0.1`

.