Last active
December 13, 2024 05:38
-
-
Save okurka12/05591c72c2141e460670ef6e542e2239 to your computer and use it in GitHub Desktop.
calculate a dobule integral using naive approach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# calculate a dobule integral using naive approach | |
# python 3.13.0 | |
# | |
# analytical solution of the example below is -7 | |
# step 0.0100: -6.9976327434199135 (44 ms) | |
# step 0.0010: -7.000145573771798 (2.7 s) | |
# step 0.0001: -7.000002405139909 (4 m 49 s) | |
# | |
# possible improvements | |
# - adapt it to use decimal | |
# - rewrite in C | |
# | |
from math import sqrt, ceil | |
# define bounds of where the area lies | |
xstart = 0.0 | |
xend = 2.0 | |
ystart = -2.0 | |
yend = 2.0 | |
# 0.01 - fast, 0.001 - doable, 0.0001 - takes ages | |
step = 0.0001 | |
# function to integrate | |
def f(x, y): | |
return y - 2 * x * sqrt(x ** 2 + y ** 2) | |
# area to integrate over (return true for x, y if the point is in the area) | |
def area(x, y): | |
return 3 <= x ** 2 + y ** 2 <= 4 and x >= 0 | |
# don't change the below | |
output = 0.0 | |
for xi in range(ceil((xend - xstart) / step)): | |
for yi in range(ceil((yend - ystart) // step)): | |
x = xstart + xi * step | |
y = ystart + yi * step | |
if area(x, y): | |
output += f(x, y) * step * step | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment