# L-25 MCS 572 Wed 23 Oct 2024 : leibnizunrolled.jl using BenchmarkTools """ The Leibniz series approximates pi/4 as 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... This example is based on section 3.2.2 on loop unrolling in Scientific Programming and Computer Architecture by Divakar Viswanath, Springer-Verlag, 2017. The branching in the straighforward code below prevents a pipelined execution of the floating-point operations. """ function leibniz1(N::Int) s = 1.0 for i=1:N if(i%2 == 1) s = s - 1.0/(2.0*i + 1.0) else s = s + 1.0/(2.0*i + 1.0) end end return s end """ The Leibniz series approximates pi/4 as 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... This example is based on section 3.2.2 on loop unrolling in Scientific Programming and Computer Architecture by Divakar Viswanath, Springer-Verlag, 2017. This second implementation (see leibniz1.jl for the first one) allows a pipelined execution of the floating-point operations. """ function leibniz2(N::Int) s = 1.0 for i=2:2:N s = s + 1.0/(2.0*i + 1.0) end for i=1:2:N s = s - 1.0/(2.0*i + 1.0) end return s end println(4.0*leibniz1(10^8)) @btime leibniz1(10^8) println(4.0*leibniz2(10^8)) @btime leibniz2(10^8)