Question

Please I need help in solving numerical differentiation, numerical integration and finding the extrema, Using PYTHON....

Please I need help in solving numerical differentiation, numerical integration and finding the extrema, Using PYTHON.

Question:

Given a function

0 0
Answer #1


Please let me know if you have any doubts or you want me to modify the answer. And if you find this answer useful then don't forget to rate my answer as thumps up. Thank you! :)


import numpy as np
import matplotlib.pyplot as plt


class Diff:
    def __init__(self, f, h=1E-5):
        self.f = f
        self.h = float(h)


class Diff2(Diff):
    def __init__(self, f, h=1E-5, dfdx_exact=None):
        Diff.__init__(self, f, h)
        self.exact = dfdx_exact

    def error(self, x):
        if self.exact is not None:
            df_numerical = self(x)
            df_exact = self.exact(x)
        return df_exact - df_numerical


class Backward1(Diff2):
    def __call__(self, x):
        f, h = self.f, self.h
        return (f(x) - f(x-h))/h


class Forward1(Diff2):
    def __call__(self, x):
        f, h = self.f, self.h
        return (f(x+h) - f(x))/h


class Forward3(Diff2):
    def __call__(self, x):
        f, h = self.f, self.h
        return (-(1./6)*f(x+2*h) + f(x+h) - 0.5*f(x) - (1./3)*f(x-h))/h


class Central2(Diff2):
    def __call__(self, x):
        f, h = self.f, self.h
        return (f(x+h) - f(x-h))/(2*h)


class Central4(Diff2):
    def __call__(self, x):
        f, h = self.f, self.h
        return (4./3)*(f(x+h) - f(x-h)) /(2*h) - (1./3)*(f(x+2*h) - f(x-2*h))/(4*h)


class Central6(Diff2):
    def __call__(self, x):
        f, h = self.f, self.h
        return (3./2) *(f(x+h) - f(x-h)) /(2*h) - (3./5) *(f(x+2*h) - f(x-2*h))/(4*h) + (1./10)*(f(x+3*h) - f(x-3*h))/(6*h)


class Integrator:
    def __init__(self, a, b, n):
        self.a, self.b, self.n = a, b, n
        self.points, self.weights = self.construct_method()

    def construct_method(self):
        raise NotImplementedError('no rule in class %s'%self.__class__.__name__)

    def integrate(self, f):
        s=0
        for i in range(len(self.weights)):
            s += self.weights[i]*f(self.points[i])
        return s

    def __call__(self, f):
        return self.integrate(f)

class Midpoint(Integrator):
    def construct_method(self):
        a, b, n = self.a, self.b, self.n
        h = (b-a)/float(n)
        x = np.linspace(a + 0.5*h, b - 0.5*h, n)
        w = np.zeros(len(x)) + h
        return x, w


class Trapezoidal(Integrator):
    def construct_method(self):
        x = np.linspace(self.a, self.b, self.n)
        h = (self.b - self.a)/float(self.n - 1)
        w = np.zeros(len(x)) + h
        w[0] /= 2
        w[-1] /= 2
        return x, w


class Simpson(Integrator):
    def construct_method(self):
        if self.n % 2 != 1:
            print('n=%d must be odd, 1 is added'% self.n)
        self.n += 1
        x = np.linspace(self.a, self.b, self.n)
        h = (self.b - self.a)/float(self.n - 1)*2
        w = np.zeros(len(x))
        w[0:self.n:2] = h*1.0/3
        w[1:self.n-1:2] = h*2.0/3
        w[0] /= 2
        w[-1] /= 2
        return x, w


class GaussLegendre2(Integrator):
    def construct_method(self):
        if self.n % 2 != 0:
            print('n=%d must be even, 1 is subtracted' % self.n)
            self.n -= 1
        nintervals = int(self.n/2.0)
        h = (self.b - self.a)/float(nintervals)
        x = np.zeros(self.n)
        sqrt3 = 1.0 / np.math.sqrt(3)
        for i in range(nintervals):
            x[2*i] = self.a + (i+0.5)*h - 0.5*sqrt3*h
            x[2*i+1] = self.a + (i+0.5)*h + 0.5*sqrt3*h
        w = np.zeros(len(x)) + h/2.0
        return x, w


class CalculusCalculator():
    def __init__(self, f, a, b, resolution= 500, differentiation_method= Backward1, integration_method= Midpoint):
        self.f, self.a, self.b = f, a, b
        self.resolution = resolution
        self.differentiation_method = differentiation_method(f)
        self.integration_method = integration_method(a, b, resolution)
        self._integral = self.integration_method(f)
        fx = [f(a)]
        lx = [a]
        minima = []
        minima_value = []
        maxima = []
        maxima_value = []
        h = (b - a) / (resolution-1)
        x = a
        for i in range(resolution-1):
            x += h
            lx.append(x)
            fx.append(f(x))
            if f(x) >= f(x-h) and f(x) >= f(x+h):
                maxima_value.append(f(x))
                maxima.append(x)
            if f(x) <= f(x-h) and f(x) <= f(x+h):
                minima_value.append(f(x))
                minima.append(x)
        lx.append(b)
        fx.append(f(b))
        self.x = lx
        self.fx = fx
        self.maxima = maxima
        self.minima = minima
        self.global_max_value = max(maxima_value + [f(a), f(b)])
        self.global_min_value = min(minima_value + [f(a), f(b)])
        self.global_max = 0
        self.global_min = 0
        for i in self.x:
            if f(i) == self.global_max_value:
                self.global_max = i
            if f(i) == self.global_min_value:
                self.global_min = i

    @property
    def integral(self):
        return self._integral

    def set_differentiation_method(self, differentiation_method):
        self.differentiation_method = differentiation_method(self.f)

    def set_integration_method(self, integration_method):
        self.integration_method = integration_method(self.a, self.b, self.resolution)
        self._integral = self.integration_method(self.f)

    def df(self, x):
        return self.differentiation_method(x)

    def plot(self):
        plt.plot(self.x, self.fx)
        plt.show()

    def plot_derivative(self):
        plt.plot(self.x, [self.df(xx) for xx in self.x])
        plt.show()

    def extrame_points(self):
        print("All minima: ", end= '')
        for x in self.minima:
            print("%.4f"%x, end= ' ')
        print()
        print("All maxima: ", end= '')
        for x in self.maxima:
            print("%.4f"%x, end= ' ')
        print()
        print("Global minimum: %.4f\nGlobal maximum:%.4f"%(self.global_min, self.global_max))

if __name__ == '__main__':
    c = CalculusCalculator(lambda x: x, 0, 6, 500)
    c.plot()
    c.plot_derivative()
    c.extrame_points()
    print(c.df(2.51))
    c.set_differentiation_method(Central4)
    print(c.df(2.51))
    c.set_integration_method(Simpson)
    print(c.integral)



alculusCalculator [/Pycharm Projects/alculusCalculator] -/CalculusCalculator.py [alculusCalculatorl alculusCalculator CalculualculusCalculator [~/PycharmProjects/alculusCalculator] - ..CalculusCalculator. py [alculusCalculator] alculusCalculator CalcalculusCalculator [~/PycharmProjects/alculusCalculator] -...CalculusCalculator.py [alculusCalculator] alculusCalculator CalcualculusCalculator [~/PycharmProjects/alculusCalculator] - ./CalculusCalculator.py [alculusCalculator] alculusCalculator CalcualculusCalculator [~/PycharmProjects/alculusCalculator] - ..CalculusCalculator. py [alculusCalculator] alculusCalculator CalcalculusCalculator [/PycharmProjects/alculusCalculator] -./CalculusCalculator.py [alculusCalculator] alculusCalculator CalculualculusCalculator [/PycharmProjects/alculusCalculator] -./CalculusCalculator. py [alculusCalculator] alculusCalculator CalculalculusCalculator [~/PycharmProjects/alculusCalculator] -CalculusCalculator.py [alculusCalculator] alculusCalculator Calculus

Know the answer?
Add Answer to:
Please I need help in solving numerical differentiation, numerical integration and finding the extrema, Using PYTHON....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT