Search code examples
pythonfunctionfor-loopderivative

Calculating the Derivative of a Function


I am brand new to programming and am really struggling to create functions in Python.

While trying to calculate a derivative, I created an np.linspace for my x values and then created an empty list for the y values. I used a for-loop to created a list of y values that are the result of passing the x values through a function. After appending the empty list with the result from the for-loop, a tried to create a function to take the derivative using a finite difference approximation. When I run the program I get an error for Invalid syntax.

What am I doing wrong?

import numpy as np
from math import *

xvalue = np.linspace(0,100,20)
yvalue = []

for i in xvalue:    
    q = i**2+4
    yvalue.append(q)  

def diff(f,x):

    n= len(x)
    y = []

    for i in range(n):

        if i == n-1:
            y.append((f[i]-f[i-1])/(x[2]-x[1]))
        else:
            y.append((f[i+1]-f[i]/(x[2]-x[1]))

    return y

print xvalue
print yvalue

diff(xvalue,yvalue)

Solution

  • These kind of syntax errors can be somewhat tricky to diagnose:

    File "path/to/my/test.py", line 20
        return y
             ^
    SyntaxError: invalid syntax
    

    Since you know that there's most likely nothing wrong with the line in question (there is nothing wrong with the return y) the next thing to do is look at the previous line. As in @ljetibo's answer, you're missing a parenthesis. If for some reason the previous line looks ok, keep going up in the file until you find the culprit.

    Having a text editor that matches parentheses can be very helpful also.

    EDIT

    As @ljetibo pointed out, if you're using IDLE, there won't be a traceback like the one above. It will instead create a prompt window with an OK button and highlight the return statement giving you a general idea of where to start looking.