# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + id="tB3CJiNv0snT" executionInfo={"status": "ok", "timestamp": 1635302679728, "user_tz": 180, "elapsed": 944, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj6Xw9kJid9xbrLXlZ-X6GkHj5jEeCPZu5k8Cburfw=s64", "userId": "04298374874242312476"}}
import numpy as np


# + id="yUZ__LtcvFO6" executionInfo={"status": "ok", "timestamp": 1635304529911, "user_tz": 180, "elapsed": 293, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj6Xw9kJid9xbrLXlZ-X6GkHj5jEeCPZu5k8Cburfw=s64", "userId": "04298374874242312476"}}
def trapezoid(f, a, b, n):
    x, h = np.linspace(a, b, n+1, retstep=True)
    for xi, fxi in zip(x, f(x)):
        print(f'{xi}\t{fxi}')
    total = 0.
    for i, xi in enumerate(x):
        total += (1 if i == 0 or i == x.shape[0] - 1 else 2) * f(xi)
    return (h/2) * total

def simpson(f, a, b, n):
    x, h = np.linspace(a, b, n+1, retstep=True)
    total = 0.
    for i, xi in enumerate(x):
        coefficient = 0.
        if i == 0 or i == x.shape[0] - 1: coefficient = 1
        elif i % 2 == 0: coefficient = 2
        else: coefficient = 4

        total += coefficient * f(xi)
    return (h/3) * total


# + colab={"base_uri": "https://localhost:8080/"} id="G9HUjWeRxByz" executionInfo={"status": "ok", "timestamp": 1635302728843, "user_tz": 180, "elapsed": 302, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj6Xw9kJid9xbrLXlZ-X6GkHj5jEeCPZu5k8Cburfw=s64", "userId": "04298374874242312476"}} outputId="d8cfb22b-dc75-453b-eff9-e626c2beda20"
p = lambda x: 5.7384 - 7.7245*x - 9.6988 * x**2 - 6.5542 * x**3 + 8.7136 * x**4 - 9.044 * x**5
simpson(p, -1.1228, 1.859, 4)

# + colab={"base_uri": "https://localhost:8080/"} id="j0B-BbpluMEF" executionInfo={"status": "ok", "timestamp": 1635304145248, "user_tz": 180, "elapsed": 300, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj6Xw9kJid9xbrLXlZ-X6GkHj5jEeCPZu5k8Cburfw=s64", "userId": "04298374874242312476"}} outputId="dccf56f8-e7d7-43dd-d894-22cb88fa5bc7"
f = lambda x: np.exp(x)

trapezoid(f, 0, 9, 12)

# + colab={"base_uri": "https://localhost:8080/"} id="NasWGePXuuPj" executionInfo={"status": "ok", "timestamp": 1635304531626, "user_tz": 180, "elapsed": 15, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gj6Xw9kJid9xbrLXlZ-X6GkHj5jEeCPZu5k8Cburfw=s64", "userId": "04298374874242312476"}} outputId="b3f0ed9f-78fa-49ed-aee0-d1b4fd94b245"
f = lambda x: x*x*np.sqrt(x*x + 1)

trapezoid(f, 1, 2, 7)

StarcoderdataJupyterScriptsDedupFiltered