X Tutup
Skip to content

Commit ed423d0

Browse files
committed
add an f2py version
1 parent 4ba57a2 commit ed423d0

File tree

4 files changed

+97
-1
lines changed

4 files changed

+97
-1
lines changed

examples/extensions/f2py/README

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Note: python >= 3.12 needs ninja and meson to build.
2+
3+
Build this as:
4+
5+
f2py -c mandel.f90 -m mandel_f2py
6+
7+
then you can `import mandel_f2py` in python.
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
subroutine mandelbrot(N, xmin, xmax, ymin, ymax, max_iter, m)
2+
3+
implicit none
4+
5+
integer, intent(in) :: N
6+
double precision, intent(in) :: xmin, xmax, ymin, ymax
7+
integer, intent(in) :: max_iter
8+
9+
integer, intent(out) :: m(N, N)
10+
11+
double complex, parameter :: i_unit = (0, 1)
12+
13+
!f2py depend(N) :: m
14+
!f2py intent(out) :: m
15+
16+
integer :: i, j, niter
17+
double precision :: x(N), y(N)
18+
double precision :: dx, dy
19+
double complex, allocatable :: c(:, :)
20+
double complex, allocatable :: z(:, :)
21+
22+
! compute coordinates
23+
dx = (xmax - xmin) / (N - 1)
24+
dy = (ymax - ymin) / (N - 1)
25+
26+
do i = 1, N
27+
x(i) = xmin + i * dx
28+
y(i) = ymin + i * dy
29+
enddo
30+
31+
allocate(c(N, N))
32+
33+
do j = 1, N
34+
do i = 1, N
35+
c(i, j) = x(i) + i_unit * y(j)
36+
enddo
37+
enddo
38+
39+
m(:, :) = 0
40+
41+
allocate(z(N, N))
42+
z(:, :) = 0.0
43+
44+
do niter = 1, max_iter
45+
46+
do j = 1, N
47+
do i = 1, N
48+
49+
if (m(i, j) == 0) then
50+
z(i, j) = z(i, j) * z(i, j) + c(i, j)
51+
52+
if (abs(z(i,j)) > 2) then
53+
m(i, j) = niter
54+
endif
55+
endif
56+
57+
enddo
58+
enddo
59+
60+
enddo
61+
62+
end subroutine mandelbrot
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import matplotlib.pyplot as plt
2+
import numpy as np
3+
4+
import mandel_f2py
5+
6+
import time
7+
8+
start = time.time()
9+
10+
xmin = -2.0
11+
xmax = 2.0
12+
ymin = -2.0
13+
ymax = 2.0
14+
15+
max_iter = 50
16+
17+
m = mandel_f2py.mandelbrot(1024, xmin, xmax, ymin, ymax, max_iter)
18+
19+
print(f"execution time = {time.time() - start}\n")
20+
21+
22+
fig, ax = plt.subplots()
23+
ax.imshow(np.transpose(m), origin="lower",
24+
extent=[xmin, xmax, ymin, ymax])
25+
26+
fig.tight_layout()
27+
fig.savefig("test.png")

examples/extensions/python/mandel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def mandelbrot(N,
1717
m = np.zeros((N, N), dtype=np.int32)
1818

1919
for i in range(max_iter):
20-
z = z**2 + c
20+
z[m == 0] = z[m == 0]**2 + c[m == 0]
2121

2222
m[np.logical_and(np.abs(z) > 2, m == 0)] = i
2323

0 commit comments

Comments
 (0)
X Tutup