The Grinnell Scheme Web:
Integer exponentiation

What about raising numbers to powers? I thought you said that there was a procedure to do that.

Yes, it's called expt. Given an integer base and an integer exponent, it computes the result of raising the base to the power of the exponent:

> (expt 12 2)
144
> (expt 2 7)
128
> (expt 4 0)
1
So why isn't listed among the integer procedures?

Because it sometimes returns a non-integer, even when given integer arguments -- specifically, when the exponent is negative and the base something other than 1:

> (expt 2 -3)
0.125
What happens when the base is zero and the exponent is non-positive?

If the base is zero and the exponent is negative, evaluating the expression is an error, but an implementation of Scheme is not required to report it. When such an error occurs, some implementations of Scheme interrupt the program and produce an error message; others simply return zero as the result of the expression and keep going, even though this is mathematically incorrect.

If both the base and the exponent are zero, the Scheme standard specifies that that result should be 1, although not all Scheme implementations conform to this specification.

Are there special procedures for squaring or cubing integers?

Perhaps there should be, since these commonly occurring special cases can generally be computed more quickly than the two-argument exponential. The Scheme standard does not require them, however. On a later page we shall see that it is easy for the programmer to add such procedures to Scheme's repertoire.


Next topic
Previous topic
Table of contents


This document is available on the World Wide Web as

http://www.math.grin.edu/~stone/scheme-web/integer-exponentiation.html


created July 23, 1995
last revised December 29, 1995

Copyright 1995 by John David Stone (stone@math.grin.edu)