Need a function that measure the proximity of a given value to a target value

158 Views Asked by At

Like the title says, I'm looking for a function that take a given value, and returns a value between 0 and 1 which measures how much the given value is near to a target value. Ideally, the returned value should increase faster when the target value is almost reached. For example, if the target is 10:

  • Input = 5; output = 0.5
  • Input = 8; output = 0.85 (more than 0.8 because we are near to the target)
  • Input = 10; output = 1 (of course)
  • Input = 15; output = 0.5 (because we have exceed the target)

Any help?


EDIT 1

  • The function only takes non negative numbers.
  • The input number can be at most twice the target number

EDIT 2

This is what have I done so far:

if (amount <= target)
    return amount / target;
else if (amount >= 2 * target)
    return 0;
else
    return 1 - ( amount % target ) / target;

It's very rudimental, and it doesn't implement the concept of "speed".


EDIT 3

The goal is to use the function for an automatic optimizer. I have a set of features, and the idea behind is to assign a score to the value assigned to each feature. The more the assigned value is near to the target value, the merrier. I'm using a maximizer to maximize the sum of the scores.

1

There are 1 best solutions below

6
On

I think the reason that there are not answers is because there are many options and it really does depend on how you are going to use this. For example, if it's for an automatic optimizer, usually you want something that goes to zero and you use a minimizer.

You don't care that it's non-differentiable at the cusp?

Based on the description so far, how about

$$f(x, x_0, a) = \exp(-a|x-x_0|)$$

First plot is for $x_0=10$ and $a=0.4$

Or you can try

$$\frac{1}{2}\left(f(x, x_0, 0.2) + f(x, x_0, 2)\right)$$

to get some accelerated "hot zone".

sharp and sharper click for full size

import numpy as np
import matplotlib.pyplot as plt

def f(x, x0, a):
    return np.exp(-a * np.abs(x-x0))

x = np.linspace(0, 20, 1001)

if True:
    plt.figure()
    plt.plot(x, f(x, 10, 0.4))
    plt.plot(x, 0.5*(f(x, 10, 0.2) + f(x, 10, 2)))
    plt.show()