Hi guys, Julia newbie here. I have a very simple question that I haven’t been able to get my head around.
I ultimately want to sum f(n)*g(n)*x[n-1]
where n ranges from 1 to a predetermined integer, where f is some function and x is a pre-determined array. I will, however, illustrate my confusion with a very simple example. Suppose I have two functions I wish to sum, f1 and f2.
f1=x->1/(x^2+1)
f2=x->1/(x^2+im)
Now, suppose I write
using BenchmarkTools
@btime f2(1)
my output is, unsurprisingly,
0.001 ns (0 allocations: 0 bytes)
Same with f1(1). If I now write
@btime f2(1) + f2(2)
I still find
0.001 ns (0 allocations: 0 bytes)
If I time
@btime sum(f2(x) for x in 1:100)
I now find
2.311 μs (0 allocations: 0 bytes)
Arithmetic with complex numbers appears to take 0.001 ns each time I time it, calling the function also takes 0.001ns, so taking that runtime at face value, summing 100 complex numbers should take less than 1 ns. Yet it is taking 1000 times what naive estimates suggest.
In addition, the code
@btime sum(f1(x) for x in 1:100)
outputs
88.168 ns (0 allocations: 0 bytes)
So, there are a few things that I want to ask.
- Why is my summation taking significantly more time than the time it takes to calculate each function and sum 100 complex numbers?
- Why is there such a large discrepancy between the real and complex functions? Complex arithmetic should not be 20 times slower.
- Is something else happening under the hood that I’m not aware of? For instance, I have read that summation incorporates special techniques to reduce cancellation errors.
- Is there a way for me to actually sum this function in <= 1 ns, as I expect to be able to do?
Any help would be greatly appreciated!