Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions src/numpy_pandas/numerical_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import math
from typing import Callable
import random
import numpy as np


def numerical_integration_rectangle(
Expand All @@ -11,11 +12,21 @@ def numerical_integration_rectangle(
if a > b:
a, b = b, a
h = (b - a) / n
result = 0.0
for i in range(n):
x = a + i * h
result += f(x)
return result * h

# Fast path: try to use numpy vectorization if f supports arrays
try:
xs = a + h * np.arange(n)
# Try: see if f accepts ndarray and returns an ndarray
ys = f(xs)
# Succeeds if ys is a numpy array (or can be summed)
return float(np.sum(ys) * h)
except Exception:
# Fallback to original loop if f is not vectorized
result = 0.0
for i in range(n):
x = a + i * h
result += f(x)
return result * h


def binomial_coefficient_recursive(n: int, k: int) -> int:
Expand Down