Never do something like
double delta, start, end;
for (double v = start; v < end; v += delta)
{
// Do something
Quote:
}
The computer cannot represent real numbers exactly - there's always some
rounding error involved. And when you perform addition multiple times, you
accumulate those errors. For example, imagine you want delta to be 1.0, but
it is actually 0.999. You do v += delta one thousand times and end up with
999, not 1000.
Better do something like
int n = (end - start) / delta;
for (int i = 0; i < n; i++)
{
double v = start + i * delta;
// Do something
Quote:
}
--
With best wishes,
Igor Tandetnik
I am writing a program that deals with the Ideal Gas Law. I have a number
of
gasses that I want to test for the pressure on a given volume container.
for (i = 0; i < recCount; ++i)
{
// Don't put a new line at the top of the output file.
if (i != 0)
output << '\n';
// Set the variables to be passed to the function pressure.
numMol = 10. / MW[i];
// Get the interval of Volume from the user.
cout << "Please enter the Volume interval for Sample #"
<< i + 1 << ": ";
cin >> interval;
// Print and write each interval Volume.
for (Volume = 1; Volume < 100; Volume += interval)
{
// find the pressure of the Gas Sample.
Pressure = pressure(Volume, Temperature, numMol);
// Display ordered pairs on the screen,
// and put them in the output file.
cout << Volume << '\t' << '\t' << Pressure << endl;
output << Volume << '\t' << Pressure << '\n';
Quote:
} // end Volume for loop.
// Print and write Volume == 100;
Volume = 100;
Pressure = pressure(Volume, Temperature, numMol);
cout << Volume << "\t\t" << Pressure << endl;
output << Volume << '\t' << Pressure;
Quote:
} // end record for loop.
This works great except for the interval of 0.1. If this is the interval it
displays and records 100 twice. Once within the Volume for loop, and once
for
the 100 finalizing routine. I have tried other fractal intervals such as
0.01
and they also work fine. Is this a problem within C++ or is there a
programming
error in the code?