Finding a problem in a computer code is often difficult, but there are many strategies that can help.
If the code fails and reports a python error, the error is normally the best hint as to what is wrong. This page lists a few errors and their likely cause.
Often the problem is serious enough to affect even the simplest problems. Try using a small number of iteration, or using a simple input function, for example a constant or linear function.
Python lets you define temporary variables you can use to build up a long expression. For example, say you want to compute the Simpson rule approximation for a panel using the formula
$$ A = \frac{1}{6}\left(f(x_i)+4 f(m_{i+1})+f(x_{i+1})\right) $$
You could write it as
A = 1.0/6.0 * ( f(x[i]) + 4 * f((x[i] + x[i+1])/2) + f(x[i+1]) )
but is is quite hard to read and debug the following would be more readable and easier to debug:
m = (x[i] + x[i+1])/2
f1 = f(x[i])
f2 = f(m)
f3 = f(x[i+1])
A = 1.0/6.0 * ( f1 + 4 * f2 + f3 )
Don’t assume the code is doing what you want, use print statements to check that it is the case. For example you can print the arguments a function is called with to understand what your code is doing:
ingredients = []
def add_to_breakfast_menu(ingredient):
print ("adding", ingredient, "to breakfast menu")
ingredients.append(ingredient)
for ingredient in ["Bread", "Butter", "Marmite", "Champain"]:
add_to_breakfast_menu(ingredient)
adding Bread to breakfast menu
adding Butter to breakfast menu
adding Marmite to breakfast menu
adding Champain to breakfast menu
This way you can check that the code is doing what you expect. One you have found the mistake you can remove the print
call.