My goal here is to repeat this code using .01 as the base, then .001, and so on 6 times. Using a while loop, how could I run the code once with .01 as the base then divide it 10? How could I repeat that process 6 times? I tried using the /= operator but I get a syntax error.
print("Computing the area under the curve x^2 x 1")
a = int(input("Enter the left end point a: x = "))
b = int(input("Enter the left end point b: x = "))
base = 0.1
x = a
total_area = 0
while a <= x and x <= b:
area = (x**2 x 1) * base
x = base
total_area = area
print("Area under the curve between 40 and 60 using dx =", '{:.0E}'.format(base) , '{:.6f}'.format(total_area))
CodePudding user response:
A for-loop alternative:
print("Computing the area under the curve x^2 x 1")
a = int(input("Enter the left end point a: x = "))
b = int(input("Enter the left end point b: x = "))
base = 0.1
iterations = 6
for i in range(iterations):
total_area = 0
x = a
while a <= x and x <= b:
area = (x**2 x 1) * base
x = base
total_area = area
print("Area under the curve between 40 and 60 using dx =", '{:.0E}'.format(base) , '{:.6f}'.format(total_area))
base /= 10
CodePudding user response:
You can use an outer while loop that repeats your code 6 times:
print("Computing the area under the curve x^2 x 1")
a = int(input("Enter the left end point a: x = "))
b = int(input("Enter the left end point b: x = "))
count = 0
base = 0.1
while count < 6:
x = a
total_area = 0
while a <= x and x <= b:
area = (x**2 x 1) * base
x = base
total_area = area
print("Area under the curve between 40 and 60 using dx =", '{:.0E}'.format(base) , '{:.6f}'.format(total_area))
base /= 10
count = 1
We initialize base
as 0.1
, and count
, the iteration we are on, as 0
. We use a while loop to repeat the remaining code until count
is equal to 6
. In other words, the code doing the Riemann Sum is repeated while count
is less than 6
. At the end of each iteration, we divide base
by 10 and increase count
by 1
to move onto the next iteration.
The output to the code is:
Computing the area under the curve x^2 x 1
Enter the left end point a: x = 1
Enter the left end point b: x = 2
Area under the curve between 40 and 60 using dx = 1E-01 4.635000
Area under the curve between 40 and 60 using dx = 1E-02 4.813350
Area under the curve between 40 and 60 using dx = 1E-03 4.838333
Area under the curve between 40 and 60 using dx = 1E-04 4.833833
Area under the curve between 40 and 60 using dx = 1E-05 4.833313
Area under the curve between 40 and 60 using dx = 1E-06 4.833338
And let's check to see if this answer is right:
∫(x^2 x 1)dx from 1 to 2 = (x^3/3 x^2/2 x) from 1 to 2 = (8/3 2 2) - (1/3 1/2 1) = (8/3 4) - (5/6 1) = 20/3 - 11/6 = 29/6 = 4.833 -> our answer is right!
I hope this answered your question! Please let me know if you have any further questions/clarification :)