Issue
I counted the integral and I want to display it on the graph, but I wonder how it should be correctly placed on the graph. It seems to me that plt.plot()
alone is not enough, or maybe I am wrong, I would like to know the correct way to display this result in a graph.
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import quad
def integral(x, a, b):
return a * np.log(x + b)
a = 3
b = 2
I = quad(integral, 1, 5, args=(a, b))
print(I)
plt.plot()
plt.show()
Solution
I assume you know calculus but not so much about programming.
matplotlib.plot
only plots data, so you have to construct an array with the datapoints you want to plot. Also the result of quad
is a pair of numbers, the definite integral approximation and an estimated bound for the numerical errors.
If you want to plot the antiderivative of a function you will have to compute the integral for each of the points you want to display.
Here is an example in which I create an array and compute the integral between each element a[i] < x < a[i+1]
, and use a cumulative sum to get the curve.
For reference I also plotted the analytic integral
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import quad
def integral(x, a, b):
return a * np.log(x + b)
def II(a, b, x0, x1 = None):
if x1 is None:
# indefinite integral
return a * ((x0 + b) * np.log(x0 + b) - x0)
else:
# definite integral
return II(a,b, x1) - II(a,b, x0)
a = 3
b = 2
# plot 100 points equally spaced for 1 < x < 5
x = np.linspace(1, 5, 100)
# The first column of I is the value of the integral, the second is the accumulated error
# I[i,0] is the integral from x[0] to x[i+1].
I = np.cumsum([quad(integral, x[i], x[i+1], args=(a, b)) for i in range(len(x) - 1)], axis=0);
# Now you can plot I
plt.plot(x[1:], I[:,0])
plt.plot(x[1:], II(a, b, x[0], x[1:]), '--r')
plt.show()
Also take the tour if you didn't already, to know how to classify the answers you receive.
I hope this answers your question.
Answered By - Bob
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.