Python: Minimizing function via loop

925 views Asked by At

My code is really simple:

import numpy

def f(x):
    return x**2 +1 

f_min=10

for x in numpy.arange(-1,10,0.1):
    if f(x)<f_min :
        f_min=f(x)
        x_min=x
    else:
        print (x_min)

It gives me the correct result (x-->0) but not only once but alot of times. Why is that and how can I keep it from doing so?

2

There are 2 answers

0
Prune On BEST ANSWER

Because you told it to. :-)

Your if statement reads:

if I have a new minimum, record the value and position;
otherwise, print the existing minimum.

Any time you don't find a new minimum, you print. Since this function has its minimum early in your range, you get a lot of output.

If you want the global minimum printed only once, then do it only once: move it outside of the loop.

for x in numpy.arange(-1,10,0.1):
    if f(x)<f_min :
        f_min=f(x)
        x_min=x

print (x_min)
1
auden On

To fix this, move the print statement out of the for loop:

import numpy

def f(x):
    return x**2 +1 

f_min=10

for x in numpy.arange(-1,10,0.1):
    if f(x)<f_min :
        f_min=f(x)
        x_min=x

print (x_min)

Why do this? Well, before, when you had the print statement in the for loop, each time the for loop went through, whenever the if statement was not true, it printed, so you got a bunch of printed things. Now, when you move it out of the for loop, it can only be printed once, and the program works as you expect.