0

I can not understand why the function gives me an incorrect result 1,000,100,000.7423575, instead of the original result is supposed to be 1,000,000,000.75. Work has given them to us, we need to implement the feature of Python, higher-order functions and built my code so so. Just mention that in some parts of the code used other code here in the community. I would be happy if you could help me solve the problem.

thank you

def summ(a, b, f, nextt):
    total = f(a) / 2.0
    while a <= b:
        total += f(a)
        a = nextt(a)
    total += f(b) / 2.0   
    return total

def Tr(fx, a, b, n):
    h = float(b - a) / n
    return summ(a, b, fx, lambda a:a + h)

print(Tr(lambda x:x**9, 0.0, 10.0, 100000)) 
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59
Silvering
  • 5
  • 1
  • 2

2 Answers2

0

Here this should work:

def trapezoidal(a, b, next, f = lambda x:x**9):
     h = float(b - a) / next
     s = 0.0
     s += f(a)/2.0

     for i in range(1, next):
         s += f(a + i * h)

     s += f(b)/2.0

     return s * h
  • thanks for that but I need that the summation part will be in another function, like I posted on the top. – Silvering Dec 15 '16 at 18:44
0

First, you are adding the values of f(a) and f(b) twice, giving 1.5 times their value, instead of half their value as you want. Try

def summ(a, b, f, nextt):
    total = f(a) / 2.0
    a = nextt(a)
    while a < b - 1e-9:
        total += f(a)
        a = nextt(a)
    total += f(b) / 2.0   
    return total

This gets rid of the extra 100,000 in your result.

Secondly, you should multiply the sum by the width of each rectangle, i.e. h:

def Tr(fx, a, b, n):
    h = float(b - a) / n
    return summ(a, b, fx, lambda a:a + h) * h

Otherwise, the results are 10000 times too large in your example (contrary to the results you posted.)

Now the result I get is 1,000,000,000.7423584. You say it should be 1,000,000,000.75. The difference is probably rounding error. Perhaps you can reduce this by just using the builtin sum function:

def Tr(fx, a, b, n):
    h = float(b - a) / n
    tot = sum(fx(a + h*i) for i in range(1, n))
    tot += (fx(a) + fx(b)) / 2.
    return tot * h

Now I get 1,000,000,000.7500008, which is pretty close to your stated result.

Nick Matteo
  • 4,453
  • 1
  • 24
  • 35