In [15]:
function enorm_simple(x)
n = 0.
for i=1:length(x)
n = n + x[i]*x[i]
end
return sqrt(n)
end
Out[15]:
enorm_simple (generic function with 1 method)
In [16]:
x = [10.^160.; 10.^100.]
@show norm(x)
@show enorm_simple(x);
norm(x) = 1.0e160
enorm_simple(x) = Inf
In [17]:
# What happens if we take a long vector too?
k = 8
err1 = zeros(k)
err2 = zeros(k)
for i=1:k
n = 10^i;
x = ones(n)*1.01;
err1[i] = abs(sqrt(n)*1.01 - norm(x));
err2[i] = abs(sqrt(n)*1.01 - enorm_simple(x));
end
using Plots
plotlyjs()
plot(10.^(1:k), err2, label="enorm")
plot!(10.^(1:k), err1, label="norm")
plot!(xscale=:log10, yscale=:log10)
Out[17]:
In [18]:
function enorm_guard1(x)
n = 1.; xmax = abs(x[1])
for i=2:length(x)
ab = abs(x[i])
if ab > xmax
n = 1 + n*(xmax/ab).^2
xmax=ab
else n += (ab/xmax).^2;
end; end
return xmax*sqrt(n)
end
Out[18]:
enorm_guard1 (generic function with 1 method)
In [20]:
# What happens if we take a long vector too?
k = 8
err1 = zeros(k)
err2 = zeros(k)
for i=1:k
n = 10^i;
x = ones(n)*1.01;
err1[i] = abs(sqrt(n)*1.01 - norm(x));
err2[i] = abs(sqrt(n)*1.01 - enorm_guard1(x));
end
using Plots
plotlyjs()
plot(10.^(1:k), err2, label="enorm")
plot!(10.^(1:k), err1, label="norm")
plot!(xscale=:log10, yscale=:log10)
Out[20]:
In [21]:
err2
Out[21]:
8-element Array{Float64,1}:
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
In [24]:
# What happens if we take a long vector too?
k = 8
err1 = zeros(k)
err2 = zeros(k)
for i=1:k
n = 10^i;
x = collect(linspace(1,2,n))
exact = sqrt(14*n^2 - 13*n)/sqrt(6*(n-1))
err1[i] = abs(exact - norm(x));
err2[i] = abs(exact - enorm_simple(x));
if i==k
@show norm(x), exact, enorm_guard1(x)
end
end
using Plots
plotlyjs()
plot(10.^(1:k), err2, label="enorm")
plot!(10.^(1:k), err1, label="norm")
plot!(xscale=:log10, yscale=:log10)
(norm(x),exact,enorm_guard1(x)) = (15275.252321974915,15275.252321974915,15275.252313719811)
Out[24]:
In [ ]: