Calculating an equation solution in C++
Question
I have a function in C++ with the following signature:
float Foo(float time, float min, float curr, float beta)
Within the function, I want to determine and return MAX in the following equation:
time = beta + (1.0f - beta) * ((MAX - curr) / (MAX - min))
To test the results, you could use the following arguments:
Foo(0.95f, 625, 800, 0.75f)
It should return 1500.
On paper, I have the steps needed to determine MAX, but I don't know how to get that working in code. If anyone can provide the code to perform this calculation, I would be extremely grateful.
0.95 = 0.75 + (1 - 0.75) * ((max - 800) / (max - 625))
0.95 = 0.75 + 0.25 * ((max - 800) / (max - 625))
0.95 - 0.75 = 0.25 * ((max - 800) / (max - 625))
0.2 = 0.25 * ((max - 800) / (max - 625))
0.2 / 0.25 = (max - 800) / (max - 625)
0.8 = (max - 800) / (max - 625)
0.8 * (max - 625) = max - 800
(0.8 * max) - (0.8 * 625) = max - 800
(0.8 * max) - 500 = max - 800
((0.8 * max) - max) - 500 = -800
((0.8 * max) - max) = -800 + 500
((0.8 * max) - max) = -300
-0.2 * max = -300
max = -300 / -0.2
max = 1500
Solution
time = beta + (1.0f - beta) * ((MAX - curr) / (MAX - min))
let's denote time with t, beta with b, curr with c, min with m, and MAX with x; we have
t = b + (1-b)(x-c)/(x-m)
(x-c)/(x-m) = (t-b)/(1-b)
(x-m)(t-b) = (x-c)(1-b)
x(t-b) - x(1-b) = m(t-b) - c(1-b)
x(t-1) = m(t-b) - c(1-b)
x = (m(t-b) - c(1-b))/(t-1)
so your function will be like this
float Foo(float time, float min, float curr, float beta)
{
return (min*(time-beta) - curr*(1-beta))/(time-1);
}
I would also recommend refraining from using the identifiers min
and time
, because they may cause clashes with std::min
and std::time
OTHER TIPS
On the paper multiply each part of the equation on (MAX - min)
, then regroup elements to get MAX=some
.
The paper and the pencil is what you usually need before writing C++ functions like in your question.