Show Sidebar Hide Sidebar

# Numerical Differentiation in Python

Learn how to differentiate a sequence or list of values numerically

#### New to Plotly?¶

Plotly's Python library is free and open source! Get started by dowloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

#### Imports¶

The tutorial below imports NumPy, Pandas, and SciPy.

In [1]:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

import numpy as np
import pandas as pd
import scipy


#### Differentiate the Sine Function¶

How to use numerical differentiation to plot the derivative of the sine function $y = sin(x)$:

In [2]:
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

dy = np.zeros(y.shape,np.float)
dy[0:-1] = np.diff(y)/np.diff(x)
dy[-1] = (y[-1] - y[-2])/(x[-1] - x[-2])

trace1 = go.Scatter(
x=x,
y=y,
mode='line',
name='sin(x)'
)

trace2 = go.Scatter(
x=x,
y=dy,
mode='line',
name='numerical derivative of sin(x)'
)

trace_data = [trace1, trace2]
py.iplot(trace_data, filename='numerical-differentiation')

Out[2]:
Still need help?