Any onr can help me
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
6 comentarios
Respuestas (1)
Jan
el 12 de Nov. de 2021
% Sum of i (i = 1:n):
s = n * (n+1) / 2
Gauss is faster and easier.
% Your solution:
y = 0;
for k = 0:n
y = y + ((n/k) * (x^k) * (a^a-x));
% ^ nope, this should be (n-k)
end
disp(y)
This cannot work: n/k is Inf, if k=0. Therefore the loop is Inf in every case.
Hint: The power operator ^ is very expensive. You can avoid it:
x = 0.98;
a = 1.2;
n = 17;
xk = x;
ank = a^(n - 1);
y = 0;
for k = 1:n
y = y + (n / k * xk * ank);
xk = xk * x;
ank = ank / a;
end
y
y = 0;
for k = 1:n
y = y + n / k * x^k * a^(n-k);
end
y
This is "much faster", but speed does not matter for such tiny problems. The accumulated rounding error is acceptable: In opposite to the sum, the product is numerically stable.
0 comentarios
Ver también
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!