Prince P - 9 months ago 73

Python Question

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

Answer

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. 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. You want to use `np.arange`

instead of `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.`

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?

```
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: