Functions¶
In [1]:
import ROOT
In [2]:
import fortranmagic
%load_ext fortranmagic
import os
import sys
import numpy as np
if sys.platform.startswith("win"):
# Depends of system, python builds, and compilers compatibility.
# See below.
f_config = "--fcompiler=gnu95 --compiler=mingw32"
else:
# For Unix, compilers are usually more compatible.
f_config = ""
# Disable only deprecated NumPy API warning without disable any APIs.
f_config += " --extra '-DNPY_NO_DEPRECATED_API=0'"
%fortran_config {f_config}
New default arguments for %fortran: --extra '-DNPY_NO_DEPRECATED_API=0'
c++¶
In [3]:
%%cpp -d
double square(double d){
return d*d;
}
int fib(int x) {
if((x==1)||(x==0)) {
return(x);
}else {
return(fib(x-1)+fib(x-2));
}
}
In [4]:
%%cpp
cout <<square(2)<<" "<<fib(30)<<endl;
4 832040
c¶
In [5]:
%%cpp
printf("%lf",square(2.));
4.000000
javascript¶
In [6]:
%%js //the next line is only necessary in jupyter notebooks
element.setAttribute('style', 'white-space: pre;');console.log=function(text){element.textContent+=text+"\n"}
function square(d){
return d*d;
}
console.log(square(2))
Python¶
In [7]:
def square(d):
return d*d;
print(square(2))
4
Fortran¶
In [8]:
%%fortran
! program and subroutine exchanged due to jupyternotebook
! program main
subroutine main()
implicit none
integer :: fib
real*8::square
print *,square(7.8d0)
print *,fib(10)
call test(5d0)
! read * ! only works in compiled program
! end program
end subroutine main
real*8 function square(d)
implicit none
real*8,intent(in)::d ! intent can be "in", "out" or "inout"
square=d*d
end function
subroutine test(d)
implicit none
real*8,intent(in)::d
print *,d
end subroutine
pure recursive integer function fib(n) result(f) ! pure make no global variables accessible
implicit none
integer, intent(in) :: n
if (n <= 1) then
f = n
else
f = fib(n-1) + fib(n-1)
end if
end function fib
In [9]:
main()
60.839999999999996
512
5.0000000000000000