A function calculating the value of expression (sin(x) - x)*x^(-3).
조회 수: 6 (최근 30일)
이전 댓글 표시
write a function (exact specification below) calculating as accurately and as quickly as possible the value of the expression f(x) = (sin(x) - x)*x^(-3).
the maximum absolute error of the results calculated using the sent function should not exceed ≈100ε,
댓글 수: 3
답변 (2개)
David Hill
2020년 4월 22일
x=.5;%whatever
n=200;
f=sum((ones(1,n+1)*x).^(0:2:2*n).*(-1).^(1:n+1)./factorial(2*(0:n)+3));
g=(sin(x)-x)*x^-3;
h=abs(f-g)<10*eps;
댓글 수: 0
James Tursa
2020년 4월 22일
편집: James Tursa
2020년 4월 23일
So, for small values of x your code looks correct to me (although the N=200 is WAY WAY OVERKILL ... you don't need nearly this many terms). And when you compare it to extended precision from Symbolic Toolbox using vpa( ) this seems to confirm that you nailed it:
>> digits 100 % <-- use 100 digits extended precision
>> c = @(x)(sin(x)-x)/x^3
c =
function_handle with value:
@(x)(sin(x)-x)/x^3
>> c(1e-5)
ans =
-0.166667284899440 % <-- lots of cancellation error in this
>> c4(1e-5)
ans =
-0.166666666665833
>> c4(1e-5) - double(c(vpa(1e-5)))
ans =
0 % <-- compared to extended precision you nailed it down to the last bit
>>
>> c(1e-10)
ans =
0 % <-- MASSIVE cancellation error here ... lost everything
>> c4(1e-10)
ans =
-0.166666666666667
>> c4(1e-10) - double(c(vpa(1e-10)))
ans =
0 % <-- compared to extended precision you nailed it down to the last bit
So, maybe adjust your while loop to end sooner, but your Taylor Series code is correct. E.g., as soon as your terms stop contributing to the sum because they are too small, you can stop the while loop. Consider x = 1e-2. Each term is going to go down by (1e-2)^2/factorial(something) compared to the last term. It only takes a few of these terms before you are beyond 1e-16 or so and they stop contributing to the sum in double precision.
Was there a particular range of inputs that you are interested in? For a generic function you would probably set a threshold of input magnitude for when to calculate the function outright and when to use the Taylor Series.
When you thought you were greater than 100*eps, I think you were incorrectly comparing to the original function as written using a double input instead of comparing to an extended precision routine. As the results show above, not only is your Taylor Series code under 100*eps, it is matching the extended precision calculation down to the last bit. Can't ask for better than that!
댓글 수: 8
참고 항목
카테고리
Help Center 및 File Exchange에서 Numbers and Precision에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!