简体   繁体   English

绘制指数函数python

[英]Plotting exponential function python

I get a linear graph when trying to plot exponential function: 尝试绘制指数函数时,得到线性图:

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

def graph(formula, x_range):
   x = np.array(x_range)
   y = eval(formula)
   plt.plot(x, y)

graph('100*(np.power(0.8, x))', (0,100))

what am I doing wrong? 我究竟做错了什么? output_image output_image

You really should NOT BE USING EVAL. 您确实不应该使用评估。 However, leaving that issue aside, the problem is you are passing a tuple of two values as the argument for the x_range parameter. 但是,撇开该问题,问题在于您正在传递两个值的元组作为x_range参数的参数。 This is creating a x with the value: array([ 0, 100]) , and if you create the corresponding y's, you'll only have two points so of course you'll get a line. 这将创建一个x ,其值为: array([ 0, 100]) ,如果创建相应的y,则只有两个点,因此当然会得到一条线。 You want to use np.arange instead of np.array . 您想使用np.arange而不是np.array However, if you pass a tuple to your graph function you are going to need to unpack the tuple when you pass it to np.arange. 但是,如果将元组传递给graph函数,则将元组传递给np.arange.时,需要将其np.arange. So this should work: 所以这应该工作:

def graph(formula, x_range):
   x = np.arange(*x_range)
   y = eval(formula)
   plt.plot(x, y)

Seriously, though, instead of eval why not just pass a function? 认真地,尽管如此,为什么不仅仅传递一个函数,而不是eval

def graph(func, x_range):
   x = np.arange(*x_range)
   y = func(x)
   plt.plot(x, y)

graph(lambda x: 100*(np.power(0.8, x)), (0,100))

Results: 结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM