필터 지우기
필터 지우기

Why does this function not work for decimals?

조회 수: 1 (최근 30일)
TheSaint
TheSaint 2024년 2월 18일
이동: Dyuman Joshi 2024년 2월 18일
x = input("Please enter the value of x (in radians): ");
approximatearctan = 0;
n = 0;
arctanactual = atan(x);
while (abs(approximatearctan - atan(x))>0.00001)
approximatearctan = approximatearctan + (-1)^n * x^(2*n +1) / factorial(2*n+1);
n = n + 1;
end
fprintf('The actual value for arctan(x) to eight decimal places given an input of %0.1f is %0.8f. \n', x, arctanactual)
fprintf('The approximate value of arctan(x) to eight decimal places given an input of %0.1f is %0.8f. \n', x, approximatearctan)
fprintf('The number of terms required to reach a five decimal place agreement between the approximate and actual values of arctan(x) is %0.0f \n', n)
I have this code, and it works fine for any number above one. However, I need it to work for numbers smaller than 1, e.g. 0.7. Whenever I put in a number that is <1, the program just gets stuck in an endless running state. Any input is appreciated.
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2024년 2월 18일
이동: Dyuman Joshi 2024년 2월 18일
The formula you have used is incorrect. There is no factorial in the formula.
Refer to this webpage for expansion of arc tan for different values - https://proofwiki.org/wiki/Power_Series_Expansion_for_Real_Arctangent_Function

댓글을 달려면 로그인하십시오.

채택된 답변

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2024년 2월 18일
Here is the corrected answer (Note abs(x)<=1):
% x = input("Please enter the value of x (in radians): "); % Here "input" prompt does
% not work, but it works in a MATLAB desktop:
% E.g.:
x = pi/4;
approximatearctan = 0;
n=0;
arctanactual = atan(x);
approximatearctan = 0;
while abs(approximatearctan - arctanactual)>1e-8
approximatearctan= approximatearctan + ((-1)^n * x^(2*n + 1)) / (2*n + 1);
n = n+1;
end
fprintf('The actual value for arctan(x) at x = %0.1f is %0.8f \n', x, arctanactual)
The actual value for arctan(x) at x = 0.8 is 0.66577375
fprintf('The approximate value of arctan(x): %0.1f is %0.8f \n', x, approximatearctan)
The approximate value of arctan(x): 0.8 is 0.66577376
fprintf('The number of terms required: %d \n',n)
The number of terms required: 29
fprintf('The difference is %1.8f \n', abs(approximatearctan - arctanactual))
The difference is 0.00000001

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Quadratic Programming and Cone Programming에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by