2017-10-13 1 views
0

저는 파이썬에서 다른 함수의 변수를 다시 계산하는 함수를 작성하려고합니다. Excel 해석기와 비슷합니다.파이썬을 사용하여 변수를 다시 푸시합니다.

예를 단순화하기 위해 함수에 여러 변수를 사용하여 가격을 계산했습니다. 이 함수에 실제 값 (a, b, c, d, x)을 전달하여 숫자 값을 반환합니다.

def calc_price(a,b,c,d,x): 
    value = a+b*c-d + x 
    return value 

이제 목표 가격이 주어졌고, a, b, c, d가되었습니다. 오직 변수 x는 알려지지 않으므로 변수 x를 푸시하고 싶습니다. calc_price와 동일한 변수에 target_price라는 추가 변수를 사용하는 함수로 작성하려고합니다.

def solve(target_price, a,b,c,d): 
    #this function takes in values for target_price, a,b,c,d 
    #and should do something like this: 
    target_price = calc_price(a,b,c,d,x) 
    solve for x <---------this is the part I'm not sure how to do 
    return x 

나는 루프로 값 x를 해결 백업하려면 다음과 같은 기능을 생성하지만, 대규모 데이터 세트를 계산에서 비효율적이다, 그래서 더 효율적인 솔루션을 찾고 있어요.

def solve(target_price,a,b,c,d): 
    x = 0.01 
    while x < 1: 
     if abs(target_price - calc_price(a,b,c,d,x)) < 0.001: 
      return x 
     x += 0.001 

고마워요!

+1

[scipy.optimize.minimize_scalar (https://docs.scipy.org/doc/scipy-0.19.1/reference/generated /scipy.optimize.minimize_scalar.html). 그것은 골드 표준이 될 것입니다 (수치 적 방법에서, 다른 세계에 대한 컴퓨터 대수학 시스템을 반드시 찾아 볼 필요는 없습니다). 너무 무거운 코드/lib 의존성이라면 : root-finding과 co. – sascha

+1

@sascha, '황금'표준을 의미하지는 마세요 :-) https://docs.scipy.org/doc/scipy-0.19.1/reference/optimize.minimize_scalar-golden.html –

+0

아주 좋은 스튜어트. 하지만 브렌트 (적어도 누군가가 이미 나를 구현했을 때) :-) – sascha

답변

0

이 데모를 고려해보십시오 (귀하의 작업은 아직 명확하지 않으므로) scipy's docs을 읽으면 이러한 방법이 제공하는 기본적인 보증에 대해 알아볼 수 있습니다.

root-finding에 기반한 접근 방식이 더 적절하다고 주장 할 수 있습니다 (여기에서 함수를 최소화하므로 나머지 함수의 abs 구조). 그러나이 방법은 여기에 일부 브라케팅을 사용하지 않아도됩니다. 간격.

번호 :

import numpy as np 
from scipy.optimize import minimize_scalar 
np.random.seed(0) 

""" Utils """ 
def calc_price(x, a, b, c, d): 
    value = a+b*c-d + x 
    return value 

def calc_price_res(x, target, a, b, c, d): 
    value = a+b*c-d + x 
    return abs(value - target) # we are looking for f(x) == 0 

""" Create fake-data (typically the job of OP!) """ 
a, b, c, d, x = np.random.random(size=5) 
fake_target = calc_price(x, a, b, c, d) 

print('a, b, c, d: ', a, b, c, d) 
print('real x: ', x) 
print('target: ', fake_target) 
print('noisy obj (just to be sure): ', calc_price_res(x, fake_target, a, b, c, d)) 

""" Solve """ 
res = minimize_scalar(calc_price_res, args=(fake_target, a, b, c, d)) 

print('optimized x: ', res.x) 
print('optimized fun: ', res.fun) 

출력 :

a, b, c, d: 0.548813503927 0.715189366372 0.602763376072 0.544883182997 
real x: 0.423654799339 
target: 0.858675077275 
noisy obj (just to be sure): 0.0 
optimized x: 0.423654796297 
optimized fun: 3.04165614917e-09 
+1

고마워요. 정확히 제가 찾고 있던 것이 었습니다. 다른 변수를 전달하는 방법을 잘 모르겠지만 예제에서 매우 명확하게 나타 냈습니다! 이 minimize_scalar 함수는 원래 함수보다 훨씬 빠릅니다. – jingz

관련 문제