Below is my Code:
function bisection(custom_func,starting::T,ending::K) where {T<:Real,K<:Real}
if custom_func(starting)==0
return starting
elseif custom_func(ending)==0
return ending
elseif !_root_finder(starting,ending)
print("Cannot find roots between a and b")
return Nothing
else
mid_point = _get_mid_point(starting,ending)
while !_root_evaluate(mid_point)
if _root_finder(starting,mid_point)
ending = mid_point
elseif _root_finder(mid_point,ending)
starting = mid_point
end
mid_point = _get_mid_point(starting,ending)
end
return mid_point
end
end
function _get_mid_point(x::T, y::K) where {T<:Real,K<:Real}
return x+(y-x)/2
end
function _root_evaluate(x::T) where {T<:Real}
value = custom_func(x)
abs_value = abs(value)
return abs_value<10^-7
end
function _root_finder(x::T, y::K) where {T<:Real,K<:Real}
x,y = custom_func(x), custom_func(y)
return x * y < 0
end
function custom_func(x::T) where {T<:Real}
return x^4-4x^3+x+4
end
Below are the execution Times.
All the above cells are ran sequentially.
@time bisection(custom_func,0,3)
For the first call it takes 31 ms. (Relatively Higher, Because it will be compiled and execute)
@time bisection(custom_func,0,2.4)
For the second call it takes 28 us. (Lesser, May be because it is already compiled)
@time bisection(custom_func,0,2)
For the third call it takes 10ms. (Higher than the second call, could be long computation as there are changes in arguments)
@time bisection(custom_func,0,2)
Surprisingly now for the fourth call it only takes 26us for the same set of arguments as previously run.
Can the community please help me in understanding why there is inconsistency in execution times. Also please let me know if my understanding is right on the first call remarks (i.e, execution time is higher because it should be compiled)
Thanks,
Akhil