Piecewise functions

Some code for the characteristic function:

import numpy as np
from scipy.integrate import quad
import matplotlib.pyplot as plt

# characteristic function of interval [a,b]
def Char(x,a,b):
	y+= ((x>=a)&(x<b)) *1
	y+=(( x<a)&(x>b)) *0
	return y
# integrate the characteristic function of [-1,1]
u = lambda x: Char(x,-1,1)
integral= quad( u ,-2,2)[0]
print "The integral is %r." %integral

# plot the characteristic function of [-1,1,5]
x = np.arange(-2.0, 2.0, .01)
y= Char(x,-1,1.5)

plt.xlim( (-2,2) )
plt.ylim( (-1,2) )
This entry was posted in Paul learns python. Bookmark the permalink.

Leave a comment here

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s