1

我正在尝试计算f(x)评估的次数,而不必过多地更改我的代码,看起来应该不是很困难,但我似乎无法弄清楚。

def f (x):
    f = 12*x**5-45*x**4+40*x**3+5
    return f
def bounding():
    d=.1
    x=6
    n=0

while(n<50):
    Lb=x-d
    n+=1
    Ub=x+d
    if f(Lb)>=f(x) and f(Ub)<=f(x):
        x=x+d           
    elif f(Lb)<=f(x) and f(Ub)>=f(x):
        x=x-d           
    elif f(Lb)>=f(x) and f(Ub)>=f(x):
        print("Lower bound:",Lb,"Upperbound:",Ub)
        break
    print (n)
bounding()
4

2 回答 2

2

基于装饰器的解决方案,您可以将其应用于您想要的任何功能......

def count(fn):
        def wrapper(*args, **kwargs):
            wrapper.called+= 1
            return fn(*args, **kwargs)
        wrapper.called= 0
        wrapper.__name__= fn.__name__
        return wrapper

@count
def test():
    print "something"

test()

print test.called #will print 1
于 2015-10-24T00:37:46.623 回答
0
class F:
    count = 0
    def __call__(self, x):
        self.count += 1
        return 12*x**5-45*x**4+40*x**3+5

f = F()

从这里开始和以前一样,计数由 给出f.count。测试:)

>>> f = F()
>>> f(1)
12
>>> f(2)
-11
>>> f.count
2
>>> f(2)
-11
>>> f.count
3
于 2015-10-23T23:46:52.963 回答