The purpose of this assignment is to learn about while and for loops. Even if yo
ID: 3168371 • Letter: T
Question
The purpose of this assignment is to learn about while and for loops. Even if you know about xrange, arange, 1inspace, and similar indexing and interval functions, you may not use them. You may not use range in the exercises involving the while loop. 1. Consider in mathematical notation, not python) the interval (a, b Sup- pose you want to divide this interval into n sub-intervals of equal length, (zo, x1), (x1,xa), . . . , (z,,Fm) where zo = a and = b. For i = 0.1, n, figure out a formula (mathematically) for r, as a function of i, a, b, and n. Write a sequence of python statements that will calculate the value of the n points using a while loop you may want to add some other code here while # some test is true # do some stuff to calculate the next x value print i, x Verify that your loop works with the intervals (a, b)-(7,10 (n-3); (12,19.5) (n=10); and (0.2x), n = 8. 2. Write a function MakeSubint (a, b, n) that returns a list of the endpoints of the subintervals, e.g, MakeSubint (7,10, 3) should return the list [7,8,9,10 Verify that your function works with the same data used in the previous exercise. Use a while loop. Verify with the same data as in ex. 1 3. Write a function MakeSubintF (a, b,n) as in the previous exercise, this time using a for loop. Verify it with the same data.Explanation / Answer
import math
print('n = 3')
print('--------------------')
a = 7
b = 10
n = 3
i = 0
while i<=n:
if i==0:
x = a
print(i, x)
i += 1
x = x + (b-a)/n
print(' n = 10')
print('--------------------')
a = 12
b = 19.5
n = 10
i = 0
while i<=n:
if i==0:
x = a
print(i, x)
i += 1
x = x + (b-a)/n
print(' n = 8')
print('--------------------')
a = 0
b = 2*(math.pi)
n = 8
i = 0
while i<=n:
if i==0:
x = a
print(i, x)
i += 1
x = x + (b-a)/n
def MakeSubint(a,b,n):
ret = list()
i = 0
while i<=n:
if i==0:
x = a
ret.append(x)
i += 1
x = x + (b-a)/n
return ret
print(' a = 7, b = 10, n = 3')
print('----------------------------')
print(MakeSubint(7,10,3))
print(' a = 12, b = 19.5, n = 10')
print('----------------------------')
print(MakeSubint(12,19.5,10))
print(' a = 0, b = 2*pi, n = 8')
print('----------------------------')
print(MakeSubint(0,2*math.pi,8))
def MakeSubintF(a,b,n):
ret = list()
for i in range(n+1):
if i==0:
x = a
ret.append(x)
i += 1
x = x + (b-a)/n
return ret
print(' a = 7, b = 10, n = 3 FOR')
print('----------------------------')
print(MakeSubintF(7,10,3))
print(' a = 12, b = 19.5, n = 10 FOR')
print('----------------------------')
print(MakeSubintF(12,19.5,10))
print(' a = 0, b = 2*pi, n = 8 FOR')
print('----------------------------')
print(MakeSubintF(0,2*math.pi,8))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.