-1
import numpy as np
x = np.array([1,2,3,4,5,6,7])
f1= np.array([1,2,3,4,5,6,7])
f2= np.array([1,2,3,4,5,6,7])

def func(w1,w2,x,f1,f2):
    w1=1-w2
    return np.std(x/(w1*f1+w2*f2))

i need my code to minimize func(w1,w2,x,f1,f2) by changing w1 and w2 then give me w1 and w2 values. w1 + w2 should be equal to 1.

Chris
  • 15,819
  • 3
  • 24
  • 37
  • This is unclear, how do you want the function to look? `func(x, f1, f2)`? what will be `w1` and `w2`? – Guy Sep 15 '22 at 13:43
  • Why pass `w1` as a parameter when it is ignored anyway? Are you trying to find the value of `w2` that minimizes the return value for a given `x`, `f1`, and `f2`? – Stuart Sep 15 '22 at 13:47

1 Answers1

0

Something like this might be what you need:

x = np.random.randint(1, 10, 7)
f1 = np.random.randint(1, 10, 7)
f2 = np.random.randint(1, 10, 7)

def func(w, x, f1, f2):  # no need to pass w1 and w2 separately
    return np.std(x / (w[0] * f1 + (1 - w[0]) * f2))

res = scipy.optimize.minimize(func, x0=[0.5], args=(x, f1, f2), bounds=[(0, 1)])
w1 = res.x[0]
w2 = 1 - w1
print("Optimal weights are", w1, w2)
Stuart
  • 9,597
  • 1
  • 21
  • 30