1

I am trying to count the number of times that f(x) is evaluated without having to change my code too much, it doesn't seem like it should be very difficult but I can't seem to figure it out.

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()
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
kfredc
  • 11
  • 1
  • I'm not sure exactly what you're asking, but your code has a lot of redundant stuff in it, like the entire `bounding()` function. – TigerhawkT3 Oct 23 '15 at 23:31
  • When `def f(x)` is evaluated, the function is created. That only happens once in your code. Do you mean the number of times the function `f` is called and executed? – jpmc26 Oct 24 '15 at 01:09

2 Answers2

2

A decorator based solution, that you can apply to any function you want...

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
labheshr
  • 2,858
  • 5
  • 23
  • 34
  • Note...this requires NO change to your function...just writing an additional decorator...which is completely outside of your function – labheshr Oct 24 '15 at 00:38
  • Why not put a sample in your code using the decorator? – jpmc26 Oct 24 '15 at 01:10
  • @jpmc26: i dont follow what you mean? i've used the decorator in my sample: its called "count" ..@count ? – labheshr Oct 24 '15 at 01:12
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()

From here on as before and the count is given by f.count. Tested :)

>>> f = F()
>>> f(1)
12
>>> f(2)
-11
>>> f.count
2
>>> f(2)
-11
>>> f.count
3
Oleg Sklyar
  • 9,834
  • 6
  • 39
  • 62