Gogo78
Gogo78

Reputation: 387

Scipy optimizer to find the minimum error sum

I've a table like this: enter image description here

My goal is using the Scipy optimize to find the right values of P1 and P2 so that my V3 is equal V1, with V3= P1+ P2. Im looking for a way to try different values of P1 and P2 to get the minimum possible value of abs(sum of error) = abs (V3-V1)

the solution using excel solver: enter image description here

but instead of having different values of P1 and P2 for each row I want a combination that gets V3 to be as close to V1 with condition of min error sum possible.

Upvotes: 0

Views: 297

Answers (1)

Michele Bastione
Michele Bastione

Reputation: 363

Look, I think I understand what you're trying to achieve, and you don't really need scipy to do it. For starters, you're not really interested in what the values of P1 and P2 are, because you really want to optimize only their sum V3, so actually any 2 numbers whose sum is the optimal V3 will do the job. Now we're left to find V3. It's actually fairly easy to do, as the aforementioned optimal value will be one of the two numbers with only one significant decimal places closest to the mean. In code:

def find_minimum_error_sum(V1):
    error = lambda x: sum(abs(i-x) for i in V1)
    adjusted_mean = (sum(V1)*10//len(V1))/10
    if error(adjusted_mean) <= error(adjusted_mean+0.1):
        return adjusted_mean
    else:
        return adjusted_mean+0.1

Call the function on the array containing your V1 values and the V3 you're looking for will be returned. Then again, any 2 numbers whose sum is V3 can be your P1 and P2. Be careful though: the function will work ONLY if every number in the array contains EXACTLY one significant decimal figure!

Edit: as Joseph Budin cleverly pointed out, you can just calculate the median of the array to find V3 straight out:

from statistics import median   
V3 = median([0.5, 0.3, 0.6, 0.5, 0.7, 0.2, 0.1])

And that's it.

Upvotes: 2

Related Questions