Reputation: 13
My program uses two functions f1(x) and f2(X) to plot data. for some reason no graph appears at the end:
def create_plot_data(f, xmin, xmax, n):
"""Computes and returns a tuple (xs, ys) where xs and ys are two
sequences"""
xs = []
ys = []
for i in range(n):
x = xmin + i * (float((xmax - xmin))/ (n - 1))
xs.append(x)
y = f(x)
ys.append(y)
return xs, ys
def f1(x):
""" Computes a function f1(x) which accepts an number x as input and
returns f(x)"""
f(x) = math.cos(2 * math.pi * x) * math.exp(-(x ** 2))
return f(x)
def f2(X):
""" Computes a function f2(x) which accepts an number x as input and
returns f(x)"""
f(x) = math.log(x + 2.1)
return f(x)
def myplot():
"""Computes and returns plots of f1(x) and f2(x) using 1001 points for x
ranging from -2 to +2."""
import pylab
import numpy as np
f1data = create_plot_data(f1, -2, 2, 1001)
f2data = create_plot-data(f2, -2, 2, 1001)
pylab.plot(f1data[0], f1data[1], label = "f1(x)") #f1data[0] refers to first item in tuple {xs, ys}
pylab.plot(f2data[0], f2data[1], "y", label = "f2(x)")
pylab.legend(loc = "upper right")
pylab.xlabel("x")
pylab.savefig("plot.png")
pylab.show()
can someone tell me how to edit this to as it appears on python please
Upvotes: 0
Views: 607
Reputation: 168616
You have a number of errors in your program:
import math
to the top of your filedef f2(X)
with def f2(x)
f(x) = /code/
. Replace f(x) = ...
/ return f(x)
with y = ...
/ return y
create_plot-data
with create_plot_data
.myplot()
. Add these lines to the end of your file:
if __name__=="__main__":
myplot()
The entire, corrected, program is here:
import math
def create_plot_data(f, xmin, xmax, n):
"""Computes and returns a tuple (xs, ys) where xs and ys are two
sequences"""
xs = []
ys = []
for i in range(n):
x = xmin + i * (float((xmax - xmin))/ (n - 1))
xs.append(x)
y = f(x)
ys.append(y)
return xs, ys
def f1(x):
""" Computes a function f1(x) which accepts an number x as input and
returns f(x)"""
y = math.cos(2 * math.pi * x) * math.exp(-(x ** 2))
return y
def f2(x):
""" Computes a function f2(x) which accepts an number x as input and
returns f(x)"""
y = math.log(x + 2.1)
return y
def myplot():
"""Computes and returns plots of f1(x) and f2(x) using 1001 points for x
ranging from -2 to +2."""
import pylab
import numpy as np
f1data = create_plot_data(f1, -2, 2, 1001)
f2data = create_plot_data(f2, -2, 2, 1001)
pylab.plot(f1data[0], f1data[1], label = "f1(x)") #f1data[0] refers to first item in tuple {xs, ys}
pylab.plot(f2data[0], f2data[1], "y", label = "f2(x)")
pylab.legend(loc = "upper right")
pylab.xlabel("x")
pylab.savefig("plot.png")
pylab.show()
if __name__=="__main__":
myplot()
Upvotes: 2