Java Reference
In-Depth Information
This equation connects the imaginary numbers (
i
) and the transcendental numbers (
e
and
π
)
to the negative numbers (-1). Euler found this expression so profound he had it inscribed
on his tombstone.
The
java.lang.Math
class contains constants
Math.E
and
Math.PI
, and the
Com-
plex
class has the constant
Complex.I
. To make the formula look better I'll use static
imports for all of them.
One final addition is necessary to make this work.
Math.E
in Java is of type double, and
I want to raise it to a
Complex
power. The easiest way to do that is to convert the double
to an instance of the
Complex
class and then use the
pow
method in the
Complex
class.
Returning to Groovy metaprogramming, I need a
power
method (which corresponds to
the
**
operator) on
Double
that takes a
Complex
argument:
Double.metaClass.power = { Complex c -> (new Complex(delegate,0)).pow(c) }
With all that machinery in place the resulting code is a bit anticlimactic, but that's a good
thing:
Complex result =
E
** (
I
*
PI
)
assert
result.real == -1
assert
result.imaginary < 1.0e-15
As usual in Groovy, accessing the
real
or
imaginary
property is equivalent to calling
the
getReal
or
getImaginary
method, respectively. The expression does generate a
real part of -1, but the imaginary part isn't exactly zero due to the round-off error associ-
atedwithJavadoubles.Onmymachineitevaluatestoanumberlessthantheboundshown,
which is certainly close enough.
There are a few additional annotations available in the Grapes system. One is
@GrabCon-
fig
, used in the next example when loading a database driver. The following script uses
the
groovy.sql.Sql
class to generate an H2 database and add some data to it:
import
groovy.sql.Sql
@GrabConfig(systemClassLoader=
true
)
@Grab(group='com.h2database', module='h2', version='1.2.140')
Sql sql = Sql.newInstance(url:'jdbc:h2:mem:',driver:'org.h2.Driver')