Dear all,
I am reading a book on how to create a procedure for solving integrants using python. It is said to create an array and apply the function over an array in order to speed up the procedure. The code provided is:
from numpy import linspace, sum
def midpoint(f, a, b, n):
h = float(b-a)/n
x = linspace(a+h/2, b-h/2, n)
return h*sum(f(x))
where f is the function to be integrated between the pioints a and b, and n is the number of iteractions.
I converted this in Julia with:
function midpoint(f, a, b, n)
h = (b-a)/n
res = 0
x = collect(range(z+h/2,stop=b-h/2,length=n) )
res = sum(f(x))
return res
end
x has been correctly generated: I set a=0, b=1, n=100 and:
julia> x
100-element Array{Float64,1}:
0.005
0.015
0.025
0.035
â‹®
0.965
0.975
0.985
0.995
and I assigned a function to f:
julia> f=x->x^3+x^2
#11 (generic function with 1 method)
But when I try the apply it:
julia> res = sum(f(x))
ERROR: MethodError: no method matching ^(::Array{Float64,1}, ::Int64)
Closest candidates are:
^(::Float16, ::Integer) at math.jl:795
^(::Missing, ::Integer) at missing.jl:120
^(::Missing, ::Number) at missing.jl:93
...
Stacktrace:
[1] macro expansion at ./none:0 [inlined]
[2] literal_pow at ./none:0 [inlined]
[3] (::getfield(Main, Symbol("##13#14")))(::Array{Float64,1}) at ./none:1
[4] top-level scope at none:0
What am I missing? how can I apply a function to all elements of an array directly?
Thank you