How can I make a transfer function for an RC circuit in python

1.8k views Asked by At

I'm fairly new to programming, but this problem happens in python and in excel as well.

I'm using the following formulas for the RC transfer function

s/(s+1) for High Pass

1/(s+1) for Low Pass

with s = jwRC

below is the code I used in python

from pylab import *
from numpy import *
from cmath import *

"""
Generating a transfer function for RC filters.
Importing modules for complex math and plotting.
"""

f = arange(1, 5000, 1)
w = 2.0j*pi*f
R=100
C=1E-5


hp_tf = (w*R*C)/(w*R*C+1)  # High Pass Transfer function
lp_tf = 1/(w*R*C+1)    # Low Pass Transfer function

plot(f, hp_tf) # plot high pass transfer function
plot(f, lp_tf, '-r') # plot low pass transfer function
xscale('log')

I can't post images yet so I can't show the plot. But the issue here is the cutoff frequency is different for each one. They should cross at y=0.707, but they actually cross at about 0.5.

I figure my formula or method is wrong somewhere, but I can't find the mistake can anyone help me out?

Also, on a related note, I tried to convert to dB scale and I get the following error:

TypeError: only length-1 arrays can be converted to Python scalars

I'm using the following

debl=20*log(hp_tf)
1

There are 1 answers

1
rth On

This is a classical example why you should avoid pylab and more generally imports of the form

 from module import *

unless you know exactly what it does, since it hopelessly clutters the name space.

Using,

import matplotlib.pyplot as plt
import numpy as np

and then calling np.log and plt.plot etc. will solve your problem.


Furether explanations

What's happening here is that,

from pylab import *

defines a log function from numpy that operate on arrays (the one you want).

However, the later import,

from cmath import *

overwrites it with a version that only accepts scalars, hence your error.