Calculating the value of arctan(x) in C++ -
i have calculate value of arctan(x)
. have calculated value of evaluating following series :
arctan (x) = x – x^3/3 + x^5/5 – x^7/7 + x^9/9 - …
but following code can not calculate actual value. example, calculate_angle(1)
returns 38.34 . why?
const double degrees_per_radian = 57.296; double calculate_angle(double x) { int power=5,count=3; double term,result,prev_res; prev_res = x; result= x-pow(x,3)/3; while(abs(result-prev_res)<1e-10) { term = pow(x,power)/power; if(count%2==0) term = term*(-1); prev_res=result; result=result+term; ++count; power+=2; // if(count=99) // break; } return result*degrees_per_radian; }
edit: found culprit. forgot include stdlib.h
, function abs
resides. must have ignored warning abs
being implicitly declared. checked removing include yields result 38.19 , including yields result ~45.
the compiler not required stop compilation when undeclared function being used (in case abs). instead, allowed make assumptions on how function declared (in case, wrong one.)
besides, other posters stated, use of abs
inappropriate returns int, not double or float. condition in while should >1e-100
not <1e-100
. 1e-100
small.
--
you forgot increase count
, power
after calculating first 2 summands:
prev_res = x; result= x-pow(x,3)/3; count = 4; <<<<<< power = 5; <<<<<< while(abs(result-prev_res)<1e-100) { term = pow(x,power)/power; if(count%2==1) term = term*(-1);
also consider use of count
variable counterintuitive: intialized 3
if denotes last used power; then, loop iterations increase 1
instead of 2
, decide sign count%2 == 1
opposed power%4 == 3
Comments
Post a Comment