TIP #123: Adding an Exponentiation Operator to the [expr] Command


TIP:123
Title:Adding an Exponentiation Operator to the [expr] Command
Version:$Revision: 1.6 $
Authors: Arjen Markus <arjen dot markus at wldelft dot nl>
Donal K. Fellows <donal dot k dot fellows at man dot ac dot uk>
State:Final
Type:Project
Tcl-Version:8.5
Vote:Done
Created:Monday, 16 December 2002
Keywords:mathematics, evaluation

Abstract

This TIP proposes to add a new operator to the operators recognised by the [expr] command: the exponentiation operator. This operator will enhance the functionality of the current pow() function by returning a result that depends on the type of its operands. It will also make complicated formulae more readable.

Introduction

Currently Tcl's [expr] command uses the exponentiation function pow() to calculate such expressions as "2 to the power 10". The drawback of this is twofold:

Other languages, like for instance FORTRAN, use an operator instead of a function. Two operators are commonly found: ** and ^. As the latter already has a meaning within the [expr] command, we propose to add the "**" operator instead. The above example would become:

 2.0*$x**3 - 1.2*$x**2 + 3.0*$x + 4.0

Mathematical Details

The implementation of the exponentiation operator will have the following properties (below we refer to the expression $x**$y):

If x and y are both integers (ordinary or wide):

If either x or y is a double, the C function pow() is used to compute the result.

The following expressions are parsed and evaluated in accordance with all other operators:

 $x ** $y ** $z ==> ($x ** $y ) ** $z
 $x ** -1       ==> ($x ** (-1))

The precedence of the exponentiation operator is thus higher than the multiplication, division and remainder operations and lower than the unary operations, in accordance with common definitions.

Sample Implementation

http://sf.net/tracker/?func=detail&aid=655176&group_id=10894&atid=310894

Copyright

This document is placed in the public domain.


Powered by Tcl[Index] [History] [HTML Format] [Source Format] [LaTeX Format] [Text Format] [XML Format] [*roff Format (experimental)] [RTF Format (experimental)]

TIP AutoGenerator - written by Donal K. Fellows