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

조회 수: 3 (최근 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