mram.py

Created by matt-numworks

Created on June 05, 2025

1.17 KB

This computes the MRAM of a function.


import numpy as np

def riemann_sum(func, a, b, n, method='midpoint'):
    """
    Calculate the Riemann sum for a given function.

    Parameters:
        func (function): The function to integrate.
        a (float): The start of the interval.
        b (float): The end of the interval.
        n (int): The number of subintervals.
        method (str): The method to use ('left', 'right', 'midpoint').

    Returns:
        float: The Riemann sum.
    """
    dx = (b - a) / n  # Width of each subinterval
    x = None

  
    if method == 'midpoint':
        x = np.linspace(a + dx / 2, b - dx / 2, n)  # Midpoints
    else:
        raise ValueError("Method must be 'midpoint'.")

    return np.sum(func(x) * dx)

# Example usage
if __name__ == "__main__":
    # Define the function to integrate
    def f(x):
        return x**2  # Example: f(x) = x^2

    # Interval [a, b] and number of subintervals
    a = 0
    b = 1
    n = 100

    # Calculate Riemann sums
    left_sum = riemann_sum(f, a, b, n, method='left')
    right_sum = riemann_sum(f, a, b, n, method='right')
    midpoint_sum = riemann_sum(f, a, b, n, method='midpoint')

    # Print results
    print(midpoint_sum)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.