while loop not taking decimal or fractional answers and unrecognized variable
Show older comments
Hi there
I am trying to write a while loop to determine convergence of a Taylor and/or Laurent series. I am not being assigned to do this, I just want to do it for myself as it would be very useful. I've found codes online for "normal" series, but I can't find one that works for a form of power series. On top of this though, I am having issues with the "normal" series code. I have started with this code I found online.
ER=100;
s=0;
n=1;
while (ER >= 0.01)
n_sum = (1/(n^2));
s = s + n_sum; %compute the running sum
ER =(abs(((pi^2)/6)-s)/((pi^2)/6))*100; %Calculate error
n = n + 1; %counter
end
disp(s)
disp(n-1)
disp(ER)
This is very useful as it calculates the error, number of times it took to converge, and the point it converged to. I want to make this more general and input 1.6448 rather than (pi^2)/6. I made the change as follows:
ER=100;
s=0;
n=1;
while (ER >= 0.01)
n_sum = (1/(n^2));
s = s + n_sum; %compute the running sum
ER =(abs(((1.6448)-s)/((1.6448))*100; %Calculate error
n = n + 1; %counter
end
disp(s)
disp(n-1)
disp(ER)
This, however, gives me an "invalid expression, when calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched dlimiters." If I enter it as a fraction, it also does not work. I am struggling to understand why. I attempted changing the error as follows as I read somewhere that there could be an issue with symbolic language? I don't know what that is as I'm fairly new, but I tried, and it didn't work.
ER=100;
s=0;
n=1;
while (double(subs(ER)) >= 0.01)
n_sum = (1/(n^2));
s = s + n_sum; %compute the running sum
ER =(abs(((1.6448)-s)/((1.6448))*100; %Calculate error
n = n + 1; %counter
end
disp(s)
disp(n-1)
disp(ER)
This also significantly slowed down the code if I put (pi)^2/6 back in.
The main goal of this is also causing errors. If I try to input a Laurent series as follows:
ER=100;
s=0;
n=1;
while (double(subs(ER)) >= 0.01)
n_sum = (x/(n*(x-n)));
s = s + n_sum; %compute the running sum
ER =(abs(((1.6448)-s)/((1.6448))*100; %Calculate error
n = n + 1; %counter
end
disp(s)
disp(n-1)
disp(ER)
I am also getting an error: "Unrecognized variable 'x'." I can't fix this as x is not defined. It's the variable in the power series. Sorry for all of the code, I would have uploaded photos if I could. Any help is appreciated!
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
