diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 00de219b3..71b90afdf 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -62,4 +62,8 @@ mukundan314
Trashtalk
-Cyrus Burt \ No newline at end of file +Cyrus Burt +
+Patrik Tesarik +
+ diff --git a/book.json b/book.json index d13710307..a0c111415 100644 --- a/book.json +++ b/book.json @@ -135,6 +135,10 @@ { "lang": "nim", "name": "Nim" + }, + { + "lang": "f90", + "name": "Fortran" } ] } diff --git a/contents/monte_carlo_integration/code/fortran/monte_carlo.f90 b/contents/monte_carlo_integration/code/fortran/monte_carlo.f90 new file mode 100644 index 000000000..6dd729378 --- /dev/null +++ b/contents/monte_carlo_integration/code/fortran/monte_carlo.f90 @@ -0,0 +1,51 @@ +FUNCTION in_circle(pos_x, pos_y, r) + IMPLICIT NONE + REAL(16), INTENT(IN) :: pos_x, pos_y, r + LOGICAL :: in_circle + + in_circle = (pos_x ** 2 + pos_y ** 2) < r ** 2 + +END FUNCTION in_circle + +PROGRAM monte_carlo + + IMPLICIT NONE + + INTERFACE + FUNCTION in_circle(pos_x, pos_y, r) + IMPLICIT NONE + REAL(16), INTENT(IN) :: pos_x, pos_y, r + LOGICAL :: in_circle + END FUNCTION in_circle + END INTERFACE + + INTEGER :: i,n + REAL(16) :: pos_x,pos_y, r, pi_est, pi_count, pi_error, pi + + ! Calculate Pi from trigonometric functions as reference + pi = DACOS(-1.d0) + n = 1000000 + r = 1d0 + pos_x = 0d0 + pos_y = 0d0 + pi_count = 0d0 + + DO i=0,n + + CALL RANDOM_NUMBER(pos_x) + CALL RANDOM_NUMBER(pos_y) + + IF (in_circle(pos_x, pos_y, r) .EQV. .TRUE.) THEN + + pi_count = pi_count + 1d0 + + END IF + END DO + + pi_est = 4d0 * pi_count / n + pi_error = 100d0 * (abs(pi_est - pi)/pi) + + WRITE(*,'(A, F12.4)') 'The pi estimate is: ', pi_est + WRITE(*,'(A, F12.4, A)') 'Percent error is: ', pi_error, ' %' + +END PROGRAM monte_carlo diff --git a/contents/monte_carlo_integration/monte_carlo_integration.md b/contents/monte_carlo_integration/monte_carlo_integration.md index d65f2eb0b..838409292 100644 --- a/contents/monte_carlo_integration/monte_carlo_integration.md +++ b/contents/monte_carlo_integration/monte_carlo_integration.md @@ -69,6 +69,8 @@ each point is tested to see whether it's in the circle or not: [import:6-7, lang:"nim"](code/nim/monte_carlo.nim) {% sample lang="ruby" %} [import:1-4, lang:"ruby"](code/ruby/monte_carlo.rb) +{% sample lang="f90" %} +[import:1-8, lang:"fortran"](code/fortran/monte_carlo.f90) {% endmethod %} If it's in the circle, we increase an internal count by one, and in the end, @@ -137,6 +139,8 @@ Feel free to submit your version via pull request, and thanks for reading! [import, lang:"nim"](code/nim/monte_carlo.nim) {% sample lang="ruby" %} [import, lang:"ruby"](code/ruby/monte_carlo.rb) +{% sample lang="f90" %} +[import, lang:"fortran"](code/fortran/monte_carlo.f90) {% endmethod %}