Function to change input from 0 - 100 to 50 - 100

186 Views Asked by At

I'm looking to write a function so when I input 100 I get 50 out on the other end. Although, when I input 0, I'd like to get out 100 on the other end.

Besides this, I need to be able to input anything between 0 - 100 and it will output the relevant counterpart within the 100 - 50.

// input 100 = 50
// input 0 = 100
2

There are 2 best solutions below

0
On

Same answer as in @Did's comment, but here's how to arrive at it systematically.

You did not specify the exact sort of behaviour you want your function to exhibit, so let's go for the simplest - namely, a linear function.

Start with the input $x \in [0,100]$.

First normalise it: $\frac{x}{100} \to [0,1]$ Here I've chosen to use "$\to [,]$" to indicate the mapping of the lower and upper ends of the original range respectively.

You want the output to trend in the opposite direction to the input. You can consider the reciprocal, but that can give some complications, plus it's not linear. Here, just negate it: $-\frac{x}{100} \to [0,-1]$

You want the output to have a range (maximum possible minus minimum possible) of $50$. So multiply that normalised variable by $50$: $-\frac{50x}{100} = -\frac{x}{2} \to [0,-50]$

Finally, you want the lower value to be $50$ and the upper value to be $100$. Just add $100$ to the previous result: $100 - \frac{x}{2} \to [100,50]$

0
On

If a linear function should be used: \begin{align} f(0)&=100\\ f(100)&=50\\ f(x)&=kx+d \end{align} Solve: \begin{align} 0k+d&=100\Rightarrow d=100\\ 100k+d&=50\Rightarrow 100(k+1)=50\Rightarrow k=-0.5 \end{align}

The transformation function is: $$ f(x)=100-0.5x $$