4.6.1 Tests on numbers
Once you have declared some numbers, assigned them to expressions and
done some arithmetic with them it is frequently desired to retrieve some
kind of information from them like asking whether that number is
integer, rational, real or complex. For those cases GiNaC provides
several useful methods. (Internally, they fall back to invocations of
certain CLN functions.)
As an example, let's construct some rational number, multiply it with
some multiple of its denominator and test what comes out:
| #include <iostream>
#include <ginac/ginac.h>
using namespace std;
using namespace GiNaC;
// some very important constants:
const numeric twentyone(21);
const numeric ten(10);
const numeric five(5);
int main()
{
numeric answer = twentyone;
answer /= five;
cout << answer.is_integer() << endl; // false, it's 21/5
answer *= ten;
cout << answer.is_integer() << endl; // true, it's 42 now!
}
|
Note that the variable answer
is constructed here as an integer
by numeric
's copy constructor, but in an intermediate step it
holds a rational number represented as integer numerator and integer
denominator. When multiplied by 10, the denominator becomes unity and
the result is automatically converted to a pure integer again.
Internally, the underlying CLN is responsible for this behavior and we
refer the reader to CLN's documentation. Suffice to say that
the same behavior applies to complex numbers as well as return values of
certain functions. Complex numbers are automatically converted to real
numbers if the imaginary part becomes zero. The full set of tests that
can be applied is listed in the following table.
Method | Returns true if the object is…
|
.is_zero()
| …equal to zero
|
.is_positive()
| …not complex and greater than 0
|
.is_negative()
| …not complex and smaller than 0
|
.is_integer()
| …a (non-complex) integer
|
.is_pos_integer()
| …an integer and greater than 0
|
.is_nonneg_integer()
| …an integer and greater equal 0
|
.is_even()
| …an even integer
|
.is_odd()
| …an odd integer
|
.is_prime()
| …a prime integer (probabilistic primality test)
|
.is_rational()
| …an exact rational number (integers are rational, too)
|
.is_real()
| …a real integer, rational or float (i.e. is not complex)
|
.is_cinteger()
| …a (complex) integer (such as 2-3*I)
|
.is_crational()
| …an exact (complex) rational number (such as 2/3+7/2*I)
|
|