On 28/02/23 18:40, John Cowan wrote:
> On Tuesday, February 28, 2023 at 1:23:38 PM UTC-5, David W Noon wrote:
[snip]
>> In particular, you might want a looping construct that does not require
>> counting but a value assessment, particularly using some transcendental
>> function. For such a loop, a floating point control variable would be
>> ideally suited.
>
> Can you give me an example?
Certainly. Here is a PL/I procedure to evaluate cube roots.
/* Function procedure to evaluate cube roots.
Copyright (C) 2023, David W. Noon. All rights reserved.
This code is released under the Berkelely License. */
CUBRT:
PROC(x_cubed) RETURNS(BIN FLOAT(53) IEEE) REORDER;
DCL x_cubed BIN FLOAT(53) IEEE BYVALUE;
DCL (epsilon,x) BIN FLOAT(53) IEEE,
ABS BUILTIN;
/* Pick off trivial ones early. */
IF x_cubed = 0 | ABS(x_cubed) = 1 THEN
RETURN(x_cubed);
epsilon = ABS(x_cubed)*1D-12;
/* Newton-Raphson iteration. */
DO x = x_cubed*2D-1
REPEAT (x + x + x_cubed/(x*x))*3.333333333333333D-1
UNTIL(ABS(x_cubed - x*x*x) <= epsilon);
/* No loop body. */
END;
RETURN(x);
END CUBRT;
Note the DO ... REPEAT ... UNTIL ... that uses a floating point control
variable with no prospect of representation errors causing the loop to
go wrong. DO-loops are not limited to counting.
Meanwhile, back to Kernighan and Plauger.
Brian Kernighan was one of the original implementers of C and P.J.
Plauger was a guru spreading the C religion. However, C does not prevent
the use of floaters in for-loops. Here is the above code implemented in
C (1999 or later standard).
/* Function to evaluate cube roots.
Copyright (C) 2023, David W. Noon All rights reserved.
This code is released under the Berkeley License. */
#include <math.h>
double cubrt(double x_cubed)
{
double x;
/* Pick off trivial ones early. */
if (x_cubed == 0.0 || fabs(x_cubed) == 1.0)
return x_cubed;
const double epsilon = fabs(x_cubed)*1e-12;
/* Use Newton-Raphson iteration. */
for (x = x_cubed*0.2;
fabs(x_cubed - x*x*x) > epsilon;
x = (x + x + x_cubed/(x*x))*0.3333333333333333)
{
/* No loop body. */
}
return x;
}
As you can see, Kernighan and Plauger do not practise what they had
earlier preached.
> In any case, the stricture in TEoPS is against *counting* with
> floating-point numbers.
Well, PL/I DO-loops and C for-loops can do more than just count.
Restricting the language to integer-only control variables would be
counterproductive for a lot of numerical work.