Home arrow Practices arrow Page 10 - Basic Data Types and Calculations

Try It Out: Floating-Point Arithmetic - Practices

This article looks at some of the basic data types that are built into C++. If you're learning how to use C++, you will want to keep reading, since you'll be using these data types in all of your programs. It is taken from chapter two of the book Beginning ANSI C++: The Complete Language, by Ivor Horton (Apress, 2004; ISBN: 1590592271).

  1. Basic Data Types and Calculations
  2. Performing Simple Calculations
  3. Try It Out: Integer Arithmetic in Action
  4. Try It Out: Fixing the Appearance of the Output
  5. Try It Out: Using Integer Variables
  6. The Assignment Operator
  7. Incrementing and Decrementing Integers
  8. Numerical Functions for Integers
  9. Floating-Point Operations
  10. Try It Out: Floating-Point Arithmetic
  11. Try It Out: Yet More Output Manipulators
  12. Working with Characters
  13. Functional Notation for Initial Values
  14. Exercises
By: Apress Publishing
Rating: starstarstarstarstar / 14
September 08, 2005

print this article



Suppose that you want to construct a circular pond in which you want to keep a number of fish. Having looked into the matter, you know that you must allow 2 square feet of surface area on the pond for every 6 inches of fish length. You need to figure out the diameter of the pond that will keep the fish happy. Hereís how you can do it:

// Program 2.6 Sizing a pond for happy fish #include#include// For square root calculation using std::cout; using std::cin; using std::sqrt;

int main() { const double fish_factor = 2.0/0.5; // Area per unit length of fish const double inches_per_foot = 12.0; const double pi = 3.14159265;

double fish_count = 0.0; // Number of fish double fish_length = 0.0; // Average length of fish

cout << "Enter the number of fish you want to keep: "; cin >> fish_count; cout << "Enter the average fish length in inches: "; cin >> fish_length; fish_length = fish_length/inches_per_foot; // Convert to feet

// Calculate the required surface area double pond_area = fish_count * fish_length * fish_factor;

// Calculate the pond diameter from the area double pond_diameter = 2.0 * sqrt(pond_area/pi);

cout << "nPond diameter required for " << fish_count << " fish is " << pond_diameter << " feet.n"; return 0; }


With input values of 20 fish with an average length of 9 inches, this example produces the following output:

Enter the number of fish you want to keep: 20 Enter the average fish length in inches: 9 Pond diameter required for 20 fish is 8.74039 feet.

You first declare threeconstvariables that youíll use in the calculation:

const double fish_factor = 2.0/0.5; // Area per unit length of fish const double inches_per_foot = 12.0; const double pi = 3.14159265;

Notice the use of a constant expression to specify the value forfish_factor. You can use any expression that produces a result of the appropriate type to define an initializing value for a variable. You have declaredfish_factor,inches_per_foot, andpiasconstbecause you donít want to allow them to be altered.

Next, you declare variables in which youíll store the user input:

double fish_count = 0.0; // Number of fish double fish_length = 0.0; // Average length of fish

You donít have to initialize these, but itís good practice to do so.

Because the input for the fish length is in inches, you need to convert it to feet before you use it in the calculation for the pond:

fish_length = fish_length/inches_per_foot; // Convert to feet

This stores the converted value back in the original variable.

You get the required area for the pond with the following statement:

double pond_area = fish_count * fish_length * fish_factor;

The product offish_countandfish_lengthgives the total length of all the fish, and multiplying this byfish_factorgives the required area.

The area of any circle is given by the formula p r2, where r is the radius. You can therefore calculate the radius of the pond as the square root of the area divided by p. The diameter is then twice the radius, and the whole calculation is carried out by this statement:

pond_diameter = 2.0 * sqrt(pond_area / pi);

74 You obtain the square root using a function thatís declared in the standard header. Thesqrt()function returns the square root of the value of the expression placed between the parentheses after the function name. In this case, the value returned is of typedoublebecause the value of the expression is of typedouble, but thereís also a version that returns the square root of afloatvalue as typefloat. Theheader contains declarations for many other standard library numerical functions, as youíll see a little later in this chapter. Youíll look into functions in detail, including how you can define your own functions, in Chapter 8. Of course, like almost all the other names in the standard library,sqrtis defined within thestdnamespace, so you have ausingdeclaration for the name at the beginning of your program file.

The last step before exitingmain()is to output the result:

cout << "nPond diameter required for " << fish_count << " fish is" << pond_diameter << " feet.n";

This outputs the pond diameter required for the number of fish specified. Working with Floating-Point Values

For most computations using floating-point values, youíll find that typedoubleis more than adequate. However, you need to be aware of the limitations and pitfalls of working with floating-point variables. If youíre not careful, your results may be inaccurate, or even incorrect. The following are common sources of errors when using floating-point values:

  • Many decimal values donít convert exactly to binary floating-point values. The small errors that occur can easily be amplified in your calculations to produce large errors.


  • Taking the difference between two nearly identical values can lose precision. If you take the difference between two values of typefloatthat differ in the sixth significant digit, youíll produce a result that may have only one or two digits of accuracy. The other significant digits that are stored may represent errors.


  • Dealing with a wide range of possible values can lead to errors. You can create an elementary illustration of this by adding two values stored as typefloatwith 7 digits of precision but in which one value is 108 times larger that the other. You can add the smaller value to the larger as many times as you like, and the larger value will be unchanged. Theheader defines constants for the floating-point types that are the smallest values that you can add to 1.0 and get a different result. The constants areFLT_EPSILON,DBL_EPSILON, andLDBL_EPSILON.


Letís see how these errors can manifest themselves in practice, albeit in a somewhat artificial situation.

Try It Out: Errors in Floating-Point Calculations

Hereís an example contrived to illustrate how the first two points can combine to produce errors:

// Program 2.7 Floating point errors

using std::cout;
using std::endl;
int main() {
float value1 = 0.1f;
float value2 = 2.1f;
value1 -= 0.09f; // Should be 0.01
value2 -= 2.09f; // Should be 0.01
cout << value1 - value2 << endl; // Should output zero
return 0;  

The value displayed should be zero, but on my computer this program produces the following:


The reason for the error is that none of the numerical values is stored exactly. If you add code to output the values ofvalue1andvalue2after theyíve been modified, you should see a discrepancy between them.

Of course, the final difference between the values ofvalue1andvalue2is a very small number, but you could be using this totally spurious value in other calculations in which the error could be amplified. If you multiply this result by 1010, say, youíll get an answer around 7.45, when the result should really be zero. Similarly, if you compare these two values, expecting them to be equal, you donít get the result you expect.

CAUTION Never rely on an exact floating-point representation of a decimal value in your program code.

Tweaking the Output

The previous program outputs the floating-point value in a very sensible fashion. It gave you 5 decimal places, and it used scientific notation (that is, a mantissa and an exponent). However, you could have chosen to have the output displayed using ďnormalĒ decimal notation by employing some more output manipulators.

>>> More Practices Articles          >>> More By Apress Publishing

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Calculating Development Project Costs
- More Techniques for Finding Things
- Finding Things
- Finishing the System`s Outlines
- The System in So Many Words
- Basic Data Types and Calculations
- What`s the Address? Pointers
- Design with ArgoUML
- Pragmatic Guidelines: Diagrams That Work
- Five-Step UML: OOAD for Short Attention Span...
- Five-Step UML: OOAD for Short Attention Span...
- Introducing UML: Object-Oriented Analysis an...
- Class and Object Diagrams
- Class Relationships
- Classes

Developer Shed Affiliates


Dev Shed Tutorial Topics: