# cython: language_level=3 # L-15 MCS 507 Mon 25 Sep 2023 : integral4pi_cdeffun.pyx """ This script applies the composite trapezoidal rule to the integral of sqrt(1-x^2) for x from 0 to 1, to obtain an approximation for pi. Type declarations have been added so the for loop will be compiled into pure C code. To avoid the construction of float objects around function calls, we declare a C-style function. """ from math import sqrt cdef double circle(double x) except *: return sqrt(1-x**2) def integral4pi(int nbvals): """ Approximates Pi with the trapezoidal rule with nbvals subintervals of [0,1]. """ cdef int i cdef double step, result step = 1.0/nbvals result = (circle(0)+circle(1))/2 for i in range(nbvals): result += circle(i*step) return 4*result*step