Riemann sum python - python

I need to make a python function where i can find the surface with the riemann sum. This is what i have , and with the feedback of my teacher i am very close to it, but it does not work as properly as i want. the teacher said also something about try-catch what means that i need to make an extra code to control the answer (if im not wrong) To find the surface the uppper and the lower limits are asked and how many rectangles you want under the line like in the program.
(edit) I have made a new program , could you guys check if this is correct.
import math
def f(x): return math.sqrt(x) #Function in the left!
a = int(input("What is the lowerlimit?:"))
b = int(input("What is the upperlimit?:"))
n = int(input("How many division intervals do you want?:"))
dx = (b-a)/n;
xi = 0;
sum = 0;
for i in range(n):
xi = xi+dx;
sum = sum + f(xi)
print("The surface under the line is ", (sum*dx))
#einde programma!
import math
def f(x):
return math.sqrt(x) #Function in the left!
def positiveinput(message):
while True:
try:
c = int(input(message))
if c <= 0:
raise ValueError
break
except ValueError:
print("Oops! That was no valid number. Try again...")
a = positiveinput("What is the lowerlimit?: ")
b = positiveinput("What is the upperlimit?: ")
c = positiveinput("How many division intervals do you want?: ")
a = int(input("What is the lowerlimit?:"))
b = int(input("What is the upperlimit?:"))
c = int(input("How many division intervals do you want?:"))
dx = float((b-a)/c)
xi = a
Sum = dx
for i in range(0,c):
xi = a - dx
Sum = Sum + f(xi)
print("The surface under the line is ", (sum*dx))

There are a few issues with the code above:
1) Most importantly, You don't actually calculate the correct answer because you are assuming that the lower limit is equal to 0. Instead of writing xi=0 you should be writing xi=a!!! (Note that this will use the far end of each rectangle to calculate the height - if you want to use the lower end, and don't want to change any other code you will need to write xi = a - dx so you start on a. (Having said that, I wouldn't do it this way, but this is how to fix this without changing anything else).
2) Validation errors: There are a few things you should check:
That the values of a, b are valid numbers (note they shouldn't really have to be integers, just numbers). You can use float() to convert something to a number, just as you would use int() to convert to an integer.
that n is an integer and is not equal to 0, as that will raise an error, when you try and divide by n,
that n is not negative, as this will result in you getting the wrong value (with the code as it is).
Having said that, I would not write the code as it is. Using a for-loop and then incrementing your value is not a very pythonic thing to do. You might be interested to learn you can actually specify a lower bound and an upper bound using the range function. Experiment with:
for i in range(3,11,0.5):
print(i)
See what happens. I'm not going to give you a full solution, as this is a homework assignment, and it will benefit you most to work it out yourself, but hopefully this points you these things will point you in the right direction.

As #Sadap said, you can try something like this:
def positiveinput(message):
while True:
try:
n = int(input(message))
if n <= 0:
raise ValueError
break
except ValueError:
print("Oops! That was no valid number. Try again...")
a = positiveinput("What is the lowerlimit?:")
b = positiveinput("What is the upperlimit?:")
n = positiveinput("How many division intervals do you want?:")
Having this code as a guide, you can complete the list of errors verification that #tim-mccurrach have written in an answer to this post. Also you can check out this link where they make the Riemann Sum in a different way. For documentation about try-catch you can enter this link.

Related

Getting 'int' object is not iterable while trying to solve for x

I am trying to solve where x = -57.8. I am new to coding, so I do not know where I am going wrong in this code. I am constantly facing either object not iterable. I have not been able to figure out why!
import math
realNumber = input("Enter a floating-point real number:")
number =int(float(realNumber))
def f(x):
for x in number:
if x<5:
print("The value of x is:",(x**2/(math.fabs(x)+2))**2)
elif x==5:
print("The value of x is:",equal=(x**2/math.fabs(x)+2))
else:
print("The value of x is:",math.sqrt(x**2/(math.fabs(x)+2)))
return(x)
print(f("-57.8"))
f("-57.8")
The core problem here is that many lines of your function have no reason to be there and act at direct cross-purposes to what you're trying to do. Don't use a for loop if you don't mean to iterate, don't convert to int when you're supposed to be operating on a float, and above all else, don't enter random lines of code when you're trying to solve a problem; they will almost never help, and they will usually just break your program.
Here is a version of the code that I think accomplishes what you're trying to do. The function f computes the value and returns it (using return) rather than printing it inside the function -- this makes it a pure mathematical function (you put a number in, you get a number out). You can then call that function in the context of a print statement to print the returned value.
import math
def f(x):
if x < 5:
return (x**2 / (math.fabs(x) + 2))**2
elif x == 5:
return x**2 / math.fabs(x) + 2
else:
return math.sqrt(x**2 / (math.fabs(x) + 2))
number = float(input("Enter a floating-point real number: "))
print("The value of f(x) is:", f(number))
import math
realNumber = input("Enter a floating-point real number:")
# Here you are converting string {ex: "2.5"} to float {ex: 2.5} then to int {ex: 2}
# You can directly cast string to int if it is possible
#number =int(float(realNumber))
number =int(realNumber)
def f(x):
#for x in number:
# x is a number {ex: 5}, you can not loop over it, so this line not required
if x<5:
print("The value of x is:",(x**2/(math.fabs(x)+2))**2)
elif x==5:
print("The value of x is:",equal=(x**2/math.fabs(x)+2))
else:
print("The value of x is:",math.sqrt(x**2/(math.fabs(x)+2)))
return(x)
# After return statement no code gets executed
# So this line not required
# Also it is calling the function itself, which is {recursion}, it can lead to infinite loop
#print(f("-57.8"))
#f("-57.8")
# you want to pass number
f(number)

Being told I have an infinite loop, but I'm unsure how to fix it. (Python Coding Course)

I'm currently in a python coding class and this is an assignment. I apparently have an infinite loop somewhere in my code, yet I can't seem to find it.
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
# At this point the program should take your now factorial and give you the fibonacci sequence
# takes your factorial and makes it the fibonacci
nterms = factorial
# first two terms
n1 = 0
n2 = 1
count = 2
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence:")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=', ')
while count < nterms:
nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1
I've used both the debugging tool and attempted to find the problem myself by running the programming and attempting various break sequences but I'm just not grasping it.
There is no infinite loop in your code, both loops will finish in finite time. What is happening is that your teacher, without looking at your code, has discovered that the finite time is very, very long and mistaken this for an infinite loop.
The reason it's taking so long is that you have misunderstood the question - "I was asked to make a program that took an integer and gave me said factorial of an integer. Then give the Fibonacci sequence of the integer" - means find the factorial and Fibonacci sequence of the same integer rather than feeding the first result into the second. Simply replace the line nterms = factorial with the line nterms = num to fix the problem.
(See comments on question for additional information used in this answer)
First, you already know what a loop is and how it works. You should review the loop in your code and make sure any variable used is defined. Since this is an assignment, this is the best I can do for you, to be honest your problem is already solved.
Maybe try enclosing your code in a function with arguments/input-variables, this way your code might run smoother and better. Hope this helps.

Issues with while loop

So this code is meant to return the final error and the final logarithm of a number inputted by a user. Now my issue is that it doesn't run the loop, it just keeps going over the same number and it never ends. I am not sure if I have my print statements in the wrong area, or if I am doing the loop wrong but I want the loop to end when the error is less then 1x10^-9. It's possible my iterations are set up wrong too, not really sure what I messed up on here.
import math
import sys
#Computing natural log of x
#x value is input here
x = float(input("Please input a positive number: "))
#If x is not positive then program will not work, so it will exit
if x<=0:
print("Your number is not positive. System Shutdown.")
sys.exit()
#Retrieving ln(x) using the math command
lnx0 = math.log(x)
#Formula for approximate ln
xfrac = (x - 1)/(x + 1)
lnx = 0 #Initializing the approximating
i=0
#This is the code to make it go until it hits the error we want
while True:
ex = 2*i - 1
lnx += 2.0* (xfrac**ex / ex)
#Counter adding 1 to it
i+=1
#This is the error
err = math.fabs(lnx0 - lnx)
if err<0.0000000001:
break
#Priting approximate ln at end of loop
print ("ln(x) at " ,x,"is: " ,lnx)
#Final Error
print ("Final error is:" ,err)
#Number of itterations
#Printing accurate version of ln(x) just to see what it should be
print ("Your accurate value of ln(x) is: " ,lnx0)
I'm assuming you're using the fourth formula on this page to approximate the log function. If so, your i is starting at the wrong value; you've initialized it to 0 here, but it needs to start at 1.
Also, if you only want output after the answer has been found, rather than once per iteration, your print functions should be de-indented so they are outside the loop. Try:
import math
import sys
#Computing natural log of x
#x value is input here
x = float(input("Please input a positive number: "))
#If x is not positive then program will not work, so it will exit
if x<=0:
print("Your number is not positive. System Shutdown.")
sys.exit()
#Retrieving ln(x) using the math command
lnx0 = math.log(x)
#Formula for approximate ln
xfrac = (x - 1)/(x + 1)
lnx = 0 #Initializing the approximating
i=1
#This is the code to make it go until it hits the error we want
while True:
ex = 2*i - 1
lnx += 2.0* (xfrac**ex / ex)
#Counter adding 1 to it
i+=1
#This is the error
err = math.fabs(lnx0 - lnx)
if err<0.0000000001:
break
#Priting approximate ln at end of loop
print ("ln(x) at " ,x,"is: " ,lnx)
#Final Error
print ("Final error is:" ,err)
#Number of itterations
#Printing accurate version of ln(x) just to see what it should be
print ("Your accurate value of ln(x) is: " ,lnx0)
Result:
Please input a positive number: 5
ln(x) at 5.0 is: 1.6094379123624052
Final error is: 7.169509430582366e-11
Your accurate value of ln(x) is: 1.6094379124341003
Thanks to DSM for identifying the formula and possible fix
There are several problems with this. The first is that your computations are incorrect. I tried entering 'e' to 9 places. Your estimate, lnx, quickly degenerates to -3.3279+ and sticks there. This dooms you to an infinite loop, because the estimate will never get near the true value.
Others have already pointed out that you haven't traced your computations with print statements. I'll add another hint from my days in numerical analysis: use a restricted "for" loop until you've debugged the computations. Then trade it in for a "while err > tolerance" loop.
To address your most recent comment, you're not getting the same numbers. The first few terms are significant, but the infinite sequence quickly drops close to 0, so the additions don't show up after about 15-20 iterations.
Also print out ex and lnx values within the loop. Especially check the first one, where your exponent is -1; I believe that you've started the loop in the wrong place.
Finally, you might find this loop form a little easier to read. Get rid of your if...break statement and use this instead:
i = 1
err = 1
tolerance = 1e-10
# This is the code to make it go until it hits the error we want
while err >= tolerance:

UnboundLocalError, and TypeError

I am a beginner. My error is UnboundLocalError: local variable 'n' referenced before assignment. I have looked for answers but I dont understand most of the code.
def numberOfSquares(n):#This is where I get the user input.
n= int(input("Please input a number higher than 1 to be the number of squares drawn."))
while n < 0:
print("Please try another number.")
n= int(input("Please input a number higher than 1 to be the number of squares drawn."))
print("Thanks for your contribution!")
def main():# I call the other function in this one, and draw n number of squares. I have not even put #the different colors on it yet.
numberOfSquares(n)
import turtle
for i in range(n):
turtle.circle(40,steps= 4)
turtle.left(45)
turtle.forward(50)
n-=1
turtle.write("Colors of the Rain")
main()
It seems that you are misusing method variables. You are passing n to numberOfSquares while you really want to get a return value instead.
def number_of_squares():
# Your code here, and finally
return n
Then in your main():
n = number_of_squares()
As to the second error, you have a typo. The method turtle.cicrle receives steps argument not step.
turtle.circle(40, steps=4)
And finally, there is a strong naming convention in python. All methods should be lower-case with underscores like number_of_squares, not camel-case (numberOfSquares).

Python for loop with adding to an equation?

I need some help in this program. I need help figuring out how to make it calculate interest for a period over ten years (including the first one). This is as far as i have gotten on my own. I would greatly appreciate some insight to this problem.
Thanks.
*The "print() is just for spacing so that the program looks cleaner.
p= int(input(" Intial Amount? "))
print()
r= float(input(" Rate? (Decimal) "))
print()
n= int(input(" Number Of Times Compunded? (Yearly) "))
print()
t= float(input(" Number Of Years? "))
A= p*(1+r/n)**(n*t)
print()
print( " Interest At Final Year","$",format(A, ',.2f'))
print()
for i in range (10):
print(format(i+1, '3')," Year","Interest","$",format(A,',.2f'))
In the body of your loop, you are not updating the values of any of the variables. You need to update A at every iteration or store the intermediate results in some other variable. As an example, see the following:
def compound_interest(r, n, initial):
current_value = initial
for i in range(n):
current_value *= (1 + r)
print(current_value)
I use the current_value variable to save the intermediate results of the loop. If I had simply done initial * (1 + r) at every iteration then the value of initial would never change; the result of the calculation must be saved if you want to keep using it.
At the very end of the program it will count 1-10 but it will have the same amount as the first calculation.
Yes, that's because the only thing that happens in that loop is the print call. You're just calculating A all at once, before you get into the loop, and then using the same A over and over again.
I need help making it add the new values to add up while the "n" and the "p" are changing.
Well, you aren't changing n or p, and I don't think you need to. But you do need to change something. If you want to print a different value of A each time through the loop, you have to recalculate next year's A based on the previous year's A, or whatever else goes into determining the right value.
For example:
for year in range (10):
jan1balance = p
for period in range(n):
p = p * (1 + r)
print(format(year+1, '3')," Year","Interest","$",format(p - jan1balance,',.2f'))
Or:
for year in range (10):
yearlyinterest = 0
for period in range(n):
periodinterest = p * r
yearlyinterest += periodinterest
p += periodinterest
print(format(year+1, '3')," Year","Interest","$",format(yearlyinterest,',.2f'))

Categories