deanie
deanie

Reputation: 1

how do i insert inputs to find value of integrals in python?

I am working a physics coursework, and I am currently stuck at this section. I've trying but I couldn't get it right. Really need help here.

Its about the trapezium rule, Question: What is the value of the integral in equation f(x)=x4*(1-x)44/(1+x^2)

this is the code I've tried, but I can not get the answer

from math import *

def f(x):
    f(x)=x**4*(1-x)**4/(1+x**2)
    return f(x)

def trap0 (f,a,b,n):
    h= float (b-a)/n
    s =0.5*( f(a)+f(b))
    for i in range (1,n):
        s=s+f(a+i*h)
    return s*h

Upvotes: 0

Views: 277

Answers (2)

Jakob Bowyer
Jakob Bowyer

Reputation: 34718

from math import *

Is considered incorrect when doing imports. Granted this is just a ten minute wonder, this style of imports are frowned upon as they clutter namespaces and overwrite local variables if they are also assigned in the module or your source.

Considering you used ** over pow() means that you don't actually need the math import to begin with. But if you are on python 2.x you might want to use.

from __future__ import division

Gareth has the right answer for the function though im just complaining about style issues

Upvotes: 0

Gareth Rees
Gareth Rees

Reputation: 65854

Your definition of f is bogus. This is all you need to write:

def f(x):
    return x**4 * (1 - x)**4 / (1 + x**2)

The rest of your code looks good to me, so long as you call trap0 with floating-point arguments for a and b.

>>> trap0(math.cos, 0.0, math.pi/2, 100)
0.99997943823960744

If you want to call it with integer a and b then things can go wrong, because f ends up doing integer division instead of floating-point division:

>>> f(4.0)
1219.7647058823529
>>> f(4)
1219

The easiest fix to is to coerce the division to be floating-point, perhaps like this:

def g(x):
    return x**4 * (1 - x)**4 / (1.0 + x**2)

>>> g(4.0) == g(4)
True

Upvotes: 2

Related Questions