0

I am trying to write a program that plots the graph for the equation

y = 5 * e^-t * cos(2 * pi * t)

I have to use import math and this is what I have:

import matplotlib.pyplot as plt

import math

x = range(10)

y = [5 * math.exp(-t) * math.cos(math.pi * 2 * t) for t in x]

plt.plot(x,y)

plt.show()

I do not get the graph that I want. I need x to increment by 0.1 but when I make range(0, 10, .1), it gives me an error that:

float cannot be interpreted as integer

How can I adjust my code so that my plot points are separated by 0.1?

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
Doc
  • 19
  • 2

1 Answers1

1

range only accepts integer values for all arguments (min, max and step) - see the documentation.

To create floating point ranges, one can use numpy.arange (source):

>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

Or do so manually with another comprehension:

>>> x = range(0, 10, 1)
>>> x_float = [0.1 * i for i in x]
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

Usage:

y = [5 * math.exp(-t) * math.cos(math.pi * 2 * t) for t in x_float] # note difference
plt.plot(x_float,y) # and here
meowgoesthedog
  • 14,670
  • 4
  • 27
  • 40