Wondering if theres a way to use pow with numbers that have negetive bases and non integer exponents.
First, check the documentation. C 2018 7.12.7.4 specifies powf
, pow
, and powl
:
The pow
functions compute x
raised to the power y
. A domain error occurs if x
is finite and negative and y
is finite and not an integer value…
Your x
, approximately ?12.4112021858, is finite and negative, and your y
, approximately .2, is finite and not an integer value. So a domain error occurs.
This means you cannot expect to get a result unless the pow
you are using specifically provides support for additional cases beyond what the C standard requires, even if .2 is exactly represented in double
.
(When there is a domain-error, an implementation-defined result is returned. This could be a NaN, a valid mathematical result, such as ?2 for pow(-32, .2)
if decimal-based floating-point is used, or something else. The implementation may also report an error via errno
or a floating-point exception. See C 2018 7.12.1 for more information.)
Second, .2 is not representable in the double
format of most C implementations. C implementations commonly use the IEEE-754 binary64 format. In this format, the closest representable value to .2 is 0.200000000000000011102230246251565404236316680908203125. For the source code pow(-12.4112021858, .2)
, the numerals are first converted to double
, and then pow
is called with arguments -12.41120218580000056363132898695766925811767578125 and
0.200000000000000011102230246251565404236316680908203125. So you are not requesting an operation that has a real-number result.
If your C implementation used a decimal-based floating-point, .2 would be representable, and it would be reasonable for pow(-12.4112021858, .2)
to return the fifth root of x
, as the fifth root is a negative real number. (This would be an extension to the standard specification of pow
, as described above.)
If you know y
is supposed to be one-fifth or a rational number p/q where q is odd, you can calculate the desired result as pow(fabs(x), y)
if p is even and copysign(pow(fabs(x), y), x)
if p is odd.
One of the comments suggesting using cpow
, but that will not produce the result you want. cpow(-12.4112021858, .2)
will return approximately 1.3388 + .9727 i. (The complex power “function” is multi-valued, but cpow
is defined to produce that result.)