I was working on a demo to solve the roots of functions (example: x^3-3*x^2+2*x=0)
and found that when negative numbers were powered by 2 4 6... they were coming out negative, when of course, they should be positive.
Even with the FPU, powers are not straight forward. A simple a^b requires a bucket full of code.
This is my candidate solution to the problem. It checks whether the exponent is odd or even, and whether the number was positive or negative and acts accordingly.
(There is still a problem with fractional powers of negative numbers - but only complex numbers can solve that one.)
If you can avoid using powers, and use multiplication wherever possible, your code will run a lot faster.
deff pow
'=======
sub esp,16
fstcw [esp]
fstcw [esp+2]
or [esp],0xc00
fldcw [esp]
'
'CHECK FOR ODD OR EVEN EXPONENT
'
(
fist dword [esp+8]
and byte [esp+8],1
jnz exit
fxch
fabs
fyl2x
fld st0
frndint
fsub st1,st0
fxch
f2xm1
fld1
faddp st1,st0
fscale
fstp st1
jmp fwd nng
)
fxch
fst dword [esp+8]
fabs
fyl2x
fld st0
frndint
fsub st1,st0
fxch
f2xm1
fld1
faddp st1,st0
fscale
fstp st1
(
and byte [esp+11],128
jz exit
fchs
)
'
.nng 'DONE
'
fldcw [esp+2]
add esp,16
end deff
print pow(-2,3)
Charles
Rare and Valuable reference for FPU programming:
http://www.website.masmforum.com/tutorials/fptute/fpuchap11.htm