Question

I'm looking for a function that interpolates a value between two values following a soft curve.

Here's an example:

enter image description here

float xLerp(float mMin, float mMax, float mFactor) { ... }

mFactor should be between 1 and 0.

How can I create a function similar to the one I drew?

Was it helpful?

Solution

As I said in comment, exponent fits quite well:

double mBase = 5; // higher = more "curvy"
double minY = pow(mBase, mMin - mBase);
double maxY = pow(mBase, mMax - mBase);
double scale = (mMax - mMin) / (maxY - minY);
double shift = mMin - minY;
return pow(mBase, mFactor - mBase) * scale + shift;

Ugh, slope is all wrong, ugly hack...

OTHER TIPS

A parabola would work.

#define ASSERT (cond) // Some assertion macro
/**
 * f(x) = a(x)^2 + 0x + c // b is zero, because no x shift.
 * f(0) = mMin == c = mMin
 * f(1) = mMax == a + mMin = mMax == a = mMax - mMin
 */
float xLerp (float mMin, float mMax, float mFactor) {
    ASSERT(0 <= mFactor && mFactor <= 1);
    float a = mMax - mMin;
    return a * mFactor * mFactor + mMin;
}

A sine wave would work.

#include <math.h>
#define ASSERT (cond) // some assertion macro
/**
 * f(x) = a * sin(x / t * PI) + b
 * f(0) = mMin == b = mMin
 * f(1) = mMax == a * sin(1/t * pi) + mMin == a * sin(pi/t) = mMax - mMin
 *        a = (mMax - mMin) / sin(pi/t)
 * (Let t == 1 for "normal" periodicity. 0 < t <= 1)
 * a = (mMax - mMin) / sin(pi/t) == a = mMax - mMin
 */
float xLerp (float mMin, float mMax, float mFactor){
    ASSERT(0 <= mFactor && mFactor <= 1);
    float a = mMax - mMin;
    return a * sin(mFactor * PI) + mMin;
}    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top