c - why math.h have pow() return double and not int -
out of curiosity know pow()
returns double
is there particular reason why math.h
has api double
argument , return value.
if have case need int
return value write own api shown below. why math.h
doesn't have api , have double pow(double,double);
or there 1 this? if answer obvious let me know delete question. couldn't figure out reason behind this.
int = pow1(2,4); int pow1(int i,int j) { int k = 1; while(j--) { k = k*i; } return k; }
anol's answer on-point , believe correct assessment why int pow()
not part of standard library, amend possibility.
the useful aspect of pow
function ability correctly (at least far floating point arithmetic concerned) perform exponentiation non-integer powers. type of behavior non-trivial implement using integer math, let alone floating point math. rather asking library implementors write both integer exponentiation routine , floating point exponentiation routine, decided ask more useful of two. helps x87 instruction set, many other fpu instruction sets, provides built-in floating point exponentiation instructions make implementation on software side trivial.
c doesn't have notion of exceptions, , no language-level global state expose things cpu flags. make overflow detection in int pow()
implementation difficult provide. in case of double pow()
, can return non-signalling nan
or infinity
in case of exceptional circumstances. there no notion of nan
or infinity
in integer world.
in case of exception, program 1 of following:
- overflow silently
- return
int_min
orint_max
- change integer pointer provided function caller
- change global state
errno
- emit
sigfpe
- provide sister function
int pow_overflow_check()
can used boilerplate call
none of these desirable. first 2 options lead hard-to-diagnose logic errors in possibly unrelated areas of program. third 1 provide annoying , cumbersome barrier use of function. fourth 1 ruin sort of reentrancy guarantee. fifth option make entire program grind halt. sixth option work well, bloat standard more, , make function more cumbersome use in third option.
further, others have stated, exponentiation integer power, if base 2, trivial implement. first year compsci student basic understanding of math should able formulate correct implementation suit use cases.
the original c language aimed squarely @ assembly programmers, , 1 of symptoms of that. common theme in language spec language library should provide things either impossible implement in-language in portable manner, or extremely non-trivial implement purely in-language, when there commonly available cpu/fpu instructions can you.
Comments
Post a Comment