Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++ Tip #16: Implicit Type Conversion Operator with a Good Piece of Pi


Implicit Type Conversion Operator with a Good Piece of Pi

double const PI =
  3.141926535897932384626433832795;  // wrong
The brains who remember pi past the fourth decimal place will quickly see that this wrong. The correct approximation of pi is:

double const PI =
  3.1415926535897932384626433832795;  // correct
I started looking for an efficient way to express pi without typing a long constant. When I programmed in FORTRAN, I specified pi through a snippet of code with the following C equivalent:

double const PI = 2.0 * acos(0.0);
However, forcing the computer to calculate pi through an arc cosine function is a little backward in light of the present-day emphasis on elegance and speed.

Several years ago when I was programming in Intel assembly language, I stumbled across the following opcode for the math coprocessor side of the Intel chip:

fldpi;  load constant onto stack, pi ( 3.14159...)
When I found this opcode, I was not using the math coprocessor side of the Intel chip, so I just placed the information in the back of my mind until recently.

Opcode fldpi pushes onto the x87 chip's stack the value constant pi, which is a 66-bit constant that is rounded to double extended-precision floating-point format (64 bit). This 66-bit value is two bits more than is allowed in a double extended-precision floating-point value. Thus the value guarantees no loss of significance in a source operand [1, 2]. Opcode fldpi has been on the math coprocessor since the days of the 387 chip.

With the above information, I derived the following function:

// inline version is reduced to two OPCODES
inline double PI()
{
  double x;  // memory location to pop too
  __asm
  {
    fldpi;  // Push pi onto the FPU register stack
    fstp x; // Copy ST(0) to m64 real and pop register stack
  }
  return x
}
This function provides an accurate and efficient means of expressing pi. However, being the lazy person that I am, I was not interested in replacing all instances of PI with a function call PI(). So I created the following class with a single method, which is an implicit type-conversion operator [3]. The class implicitly converts any instance of struct CPi into a double that has the value of pi.

Normally, I think that the implicit type-conversion operator is a dangerous tool that should not be used, but, in this case, I believe I have found an exception, where not using an implicit type-conversion operator would have made it more difficult to read the code.

struct CPi
{
  // Conversion operator
  operator double () const
  {
    double x;     // memory location to store to
    __asm fldpi;  // Load constant onto stack, pi (3.14159...)
    __asm fst x;  // Floating point store
    return x;     // must have a return value
  }
};
static Cpi PI;
With the preceding code, I can use the instance of my Cpi struct in the following way:

// Calculate the area of a circle
double Area = PI * radius * radius;
When you look at the assembly language produced by the preceding line, the call to the instance of PI is reduced to two opcodes.

This class is only for use with Microsoft Visual C++ v6.0. With a few modifications, you could create a version of the class for other compilers that work on the Intel processor.

Using this class, I have secretly replaced the old way of using constant double with an instantiated object with the same name, and no one knows the difference (that is, until they read this article).

Notes

[1] The IA-32 Intel Architecture Software Developer's Manual Volume 1: Basic Architecture, pp. 8-26, <http://developer.intel.com/>.

[2] The IA-32 Intel Architecture Software Developer's Manual, Volume 2: Instruction Set Reference, pp. 3-242.

[3] Scott Meyers. More Effective C++ (Addison-Wesley, 1995).

About the Author

Curt L. Martin holds a B.S. in Aerospace Engineering from the University of Texas at Arlington. Currently he is a software developer in the Las Vegas, NV area. His former employers include Lockheed-Martin at Johnson Space Center and Hughes Aircraft. In his spare time, he is a US Army Reserve Officer and enjoys hiking in the Southern Nevada area.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.