You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Surprisingly to me, the generator sum(x^2 for x in 0:n) appears to be constant rather than linear time, and I feel like that should probably be mentioned.
Should probably mention that the evalpoly solution is real fast, too. And that this is an example where not adding type annotations means that this will happily work with floats (though of course the answers are bunk if the float has a fractional part).
My benchmarking code:
using BenchmarkTools
# Naivesquare_of_sum1(n) =sum(1:n)^2sum_of_squares1(n) =sum(x -> x^2, 0:n)
difference1(n) =square_of_sum1(n) -sum_of_squares1(n)
# Analyticalsquare_of_sum2(n) = (n*(n+1) ÷2)^2sum_of_squares2(n) = n * (n +1) * (2n +1) ÷6difference2(n) =square_of_sum2(n) -sum_of_squares2(n)
# n111b111's solutionsquare_of_sum3(n) =evalpoly(n, (0,0,1,2,1)) ÷4sum_of_squares3(n) =evalpoly(n, (0,1,3,2)) ÷6difference3(n) =evalpoly(n, (0,-2,-3,2,3)) ÷12# Constant time generatorsquare_of_sum4(n) =square_of_sum1(n)
# This seems to be constant time, so I guess there's # a cool LLVM optimisation in here?sum_of_squares4(n) =sum(x^2for x in0:n)
difference4(n) =square_of_sum4(n) -sum_of_squares4(n)
for s in ("difference",)
for i in1:4
func =Symbol(s, i)
@info func
# Test if this is constant or linear time.# Note that the answers are all wrong at 10^5# anyway due to overflow.for x in2:5@eval@btime$func($(Expr(:$, Ref(10^x)))[])
end# Paegodu's test@eval@btime$func(n) setup=(n=rand(UInt16))
# Use in a reduction@btimemaximum($func, 1000:1000:50000)
endend
Surprisingly to me, the generator
sum(x^2 for x in 0:n)
appears to be constant rather than linear time, and I feel like that should probably be mentioned.Should probably mention that the evalpoly solution is real fast, too. And that this is an example where not adding type annotations means that this will happily work with floats (though of course the answers are bunk if the float has a fractional part).
My benchmarking code:
Example results:
The text was updated successfully, but these errors were encountered: