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

7 次查看(过去 30 天)
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?

采纳的回答

Dyuman Joshi
Dyuman Joshi 2023-5-18
编辑:Dyuman Joshi 2023-5-18
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 个评论
Torsten
Torsten 2023-5-18
编辑:Torsten 2023-5-18
Is it the purpose of the exercise to see that usual floating point arithmetic as above gives "wrong" results ?
DJ Mckenna
DJ Mckenna 2023-5-18
Error is part of it, but I am needing to compare it to some other functions as well

请先登录,再进行评论。

更多回答(1 个)

Torsten
Torsten 2023-5-18
移动:Torsten 2023-5-18
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by