我试图复制Excel的目标寻求功能,这是基于牛顿-拉夫森。
在我的例子中,我想优化一组人(包括孩子)对孩子(组/孩子)的比率,使之达到“Z”的速率目标,从而得到新的孩子数;然后随着新的孩子数的改变,随着组数的增加而减少。
示例:假设我在一个小组中有1000个人,其中包括孩子,这占了100.假设我的目标利率是12 (团体/孩子).为了解决这个问题,我需要把孩子们减少到76人,这也会使这个群体减少到923人。
伪公式是群(1000 - X) / X,虽然分母中的X值需要先计算.
代码尝试:
from scipy import optimize
# inputs
group = 1000
kids = 100
# formula
def f(x, group):
results = (group - x) / x
return results
optimize.newton(f, 100, 1000)但我不知道该如何构造这个方程。
编辑:补充说我也不知道该把新目标放在哪里.还澄清说,我希望结果不低于目标。
发布于 2020-06-09 10:29:45
你只需要简单的数学就可以做到这一点。请注意:
(people - y) / y > target因此,
people - y > target * y
people > (target + 1) * y
people / (target + 1) > y应该从群体中移除的孩子数量需要满足
kids - floor(people / (target + 1))在这种情况下,你可以得到24。因此,儿童人数等于76人,成人人数等于924人。因此,924/76 ~ 12,16 > 12。
发布于 2020-06-09 17:35:40
我通过https://github.com/DrTol/GoalSeek_Python找到了解决方案
def GoalSeek(fun,goal,x0,fTol=0.0001,MaxIter=1000):
# Goal Seek function of Excel
# via use of Line Search and Bisection Methods
# Inputs
# fun : Function to be evaluated
# goal : Expected result/output
# x0 : Initial estimate/Starting point
# Initial check
if fun(x0)==goal:
print('Exact solution found')
return x0
# Line Search Method
step_sizes=np.logspace(-1,4,6)
scopes=np.logspace(1,5,5)
vFun=np.vectorize(fun)
for scope in scopes:
break_nested=False
for step_size in step_sizes:
cApos=np.linspace(x0,x0+step_size*scope,int(scope))
cAneg=np.linspace(x0,x0-step_size*scope,int(scope))
cA=np.concatenate((cAneg[::-1],cApos[1:]),axis=0)
fA=vFun(cA)-goal
if np.any(np.diff(np.sign(fA))):
index_lb=np.nonzero(np.diff(np.sign(fA)))
if len(index_lb[0])==1:
index_ub=index_lb+np.array([1])
x_lb=np.asscalar(np.array(cA)[index_lb][0])
x_ub=np.asscalar(np.array(cA)[index_ub][0])
break_nested=True
break
else: # Two or more roots possible
index_ub=index_lb+np.array([1])
print('Other solution possible at around, x0 = ', np.array(cA)[index_lb[0][1]])
x_lb=np.asscalar(np.array(cA)[index_lb[0][0]])
x_ub=np.asscalar(np.array(cA)[index_ub[0][0]])
break_nested=True
break
if break_nested:
break
if not x_lb or not x_ub:
print('No Solution Found')
return
# Bisection Method
iter_num=0
error=10
while iter_num<MaxIter and fTol<error:
x_m=(x_lb+x_ub)/2
f_m=fun(x_m)-goal
error=abs(f_m)
if (fun(x_lb)-goal)*(f_m)<0:
x_ub=x_m
elif (fun(x_ub)-goal)*(f_m)<0:
x_lb=x_m
elif f_m==0:
print('Exact spolution found')
return x_m
else:
print('Failure in Bisection Method')
iter_num+=1
return x_m运行函数
def fun(x):
return (group - x) / x
print(GoalSeek(fun, goal, x0))https://stackoverflow.com/questions/62279605
复制相似问题