python中的代数表达式 [英] algebraic expressions in python

查看:59
本文介绍了python中的代数表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 python 处理一些相对简单的代数表达式,想知道是否有比我目前正在做的更好的绘制代数表达式的方法:

I'm working with some relatively simple algebraic expressions in python and wondered if there's a better way of plotting algebraic expressions than what I'm currently doing:

我有一个陷波滤波器的方程(下图 - 书的左侧;右侧图是我的代码生成的无花果),到目前为止我的代码虽然很粗糙.

I have the equation of a notch filter (below image - left side from a book; the right side graph is the fig generated by my code), and so far my code works though is crude.

是否有更好的绘制幅度的方法?如图所示,常数是;R = 50.0,C = 470e-12,L = 54e-6,所需频率范围为0到2MHz.

import matplotlib.pyplot as plt
import numpy as np
import math

R = 50.0
C = 470e-12
L = 54e-6

FREQ = []
DATA = []
for i in range(1, 200):
    f = i*10000.0
    w = 2*np.pi*f

    Ztop = w*L - 1.0/(w*C)
    Zbot = math.sqrt( (math.pow(R,2) + math.pow((w*L) -(1.0/(w*C)),2)) )
    Zout = abs(Ztop / Zbot)
    FREQ.append( f/1e6 )
    DATA.append( Zout )

plt.figure(1)
plt.plot(FREQ,DATA, '-k')
plt.xlabel('Frequency (MHz)')
plt.ylabel('Mag.')
plt.grid()
plt.show()

推荐答案

我建议的主要改进是使用 Numpy 的数组广播工具.基本上这将一次对整个数组执行数学运算.除此之外,您的代码没有任何错误,尽管您可以在一个表达式中计算整个幅度.这取决于您是否认为它使代码更清晰.

The main improvement I'd suggest is using Numpy's array broadcasting facility. Basically this will perform a mathematical operation on a whole array at once. Other than that, there's nothing really wrong with your code, though you could calculate the entire magnitude in one expression. That's your call, depending on whether you think it makes the code clearer.

# creates 201 values evenly spaced from 0 to 2e6, inclusive
f = np.linspace(0, 2e6, 201)
w = 2 * np.pi * f
# now calculate the magnitude for all 201 values at once
magnitude = (w * L - 1 / (w * C)) / np.sqrt(R**2 + (w * L - 1 / (w * C))**2)
# now you can plot magnitude vs. frequency
plt.plot(f / 1e6, magnitude, '-k')

这篇关于python中的代数表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆