I need to create a loop to evaluate a function at decreasing points.

I need to evaluate the function ( (e^x)-e^(-x))/x at values starting from 1e-6, 1e-7, 1e-8... to 1e-17 and have each output be stored in a table. How can I do this?

 Réponse acceptée

You can use a for loop to do that, evaluate the function at each point and store the result.
Another way is vectorize the operation, read more - Vectorization.
If you want to store the output in a specific way, please mention the output format.
format long
%define x
x = 10.^-(6:17)
x = 1×12
1.0e-06 * 1.000000000000000 0.100000000000000 0.010000000000000 0.001000000000000 0.000100000000000 0.000010000000000 0.000001000000000 0.000000100000000 0.000000010000000 0.000000001000000 0.000000000100000 0.000000000010000
f = (exp(x)-exp(-x))./x
f = 1×12
1.999999999946489 1.999999998947288 1.999999987845058 2.000000054458440 2.000000165480742 2.000000165480742 2.000066778862220 1.999511667349907 1.998401444325282 2.109423746787797 1.110223024625157 0

3 commentaires

The format would be to store the input and output in a two column table. Thanks!
Torsten
Torsten le 18 Mai 2023
Modifié(e) : Torsten le 18 Mai 2023
Is it the purpose of the exercise to see that usual floating point arithmetic as above gives "wrong" results ?
Error is part of it, but I am needing to compare it to some other functions as well

Connectez-vous pour commenter.

Plus de réponses (1)

Torsten
Torsten le 18 Mai 2023
Déplacé(e) : Torsten le 18 Mai 2023
digits(100)
vpa((exp(sym('1/10'))-exp(sym('-1/10')))/sym('1/10'))
ans = 
2.003335000396880516474587670438100470298418337571177667366059723851880014034059419766398729346581964
vpa((exp(sym('1/1000000'))-exp(sym('-1/1000000')))/sym('1/1000000'))
ans = 
2.000000000000333333333333350000000000000396825396825402336860670194053631553631553952734508290065375
vpa((exp(sym('1/10000000'))-exp(sym('-1/10000000')))/sym('1/10000000'))
ans = 
2.000000000000003333333333333335000000000000000396825396825396880511463844797183140933140933141254322
vpa((exp(sym('1/100000000000000000'))-exp(sym('-1/100000000000000000')))/sym('1/100000000000000000'))
ans = 
2.000000000000000000000000000000000033333333333333333333333333333333333499999999999999999999781236209
I think you should be able to read the documentation on how to create a table for the results.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Produits

Version

R2021b

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by