[comp.lang.c] Power

be@dde.uucp (Bjorn Engsig) (01/18/88)

A short resume for sci.math.num-analysis readers:
-- A lot of people have written pro et contra for the inclusion
-- of a power (which power? most don't bother :-) operator in the
-- C programming language.  The discussion has been on which symbol
-- to use for power, where to put it in the operator hierarchy, and
-- wether it should have integer or real exponents.  C currently includes
-- a pow function with real exponents, defined for nonnegative mantissa
-- only.

Let me start to comment on power with integer exponents.

Pick up any first grade textbook on numerical analysis, and you will
be told NEVER to use a power function like that.  First, if you need to
calculate  x ** n (fortran notation), you will most often need
x ** (n-1)  etc. as well, and it should be calculated using recursion,
to optimize calculation time.  Second, you should bear in mind,
that using ordinary polynmials is often a bad practice in numerical 
computation, since they are higly unorthogonal (i.e. similar, try to
graph  x ** 9  and  x ** 10  for  x  between  0  and  1.).  If you are
doing computations with polynomials involved, you will normally pick a
set of orthogonal polynomials, such as the chebychef polynomials.
These kinds of polynomials are always calculated by recursion for speed
and accuracy.

Thus: Power with integer exponent is not needed!

Next, the power with real exponent, which we have as the pow() function,
is according to my knowledge not very heavily used.  If a lot of people
can come up with a lot of REAL application, where the call of pow()
really makes their code look ugly compared with an infix operator, one
MIGTH consider the inclusion of the operator.  However, a lot of non
numerics will definately use this operator for integer exponention, and
they will not understand why they can't square -2.0, and why their
progam is using that much CPU time.

Thus: Power with real exponent is not good!

-- 
Bjorn Engsig, E-mail:  ..!uunet!mcvax!diku!dde!be  or  be@dde.uucp
--
Hofstadters Law: It always take longer than you expect, even if you take into
		 account Hofstadters Law.

gwyn@brl-smoke.ARPA (Doug Gwyn ) (01/19/88)

In article <302@Aragorn.dde.uucp> be@dde.uucp (Bjorn Engsig) writes:
>Pick up any first grade textbook on numerical analysis, and you will
>be told NEVER to use a power function like that.  ...
>Thus: Power with integer exponent is not needed!

That's what you get for picking up first grade textbooks!

If you do much geometric programming at all, you quickly realize
that the squaring operator (expr ** 2) is quite heavily used.

jmd@granite.dec.com (John Danskin) (01/20/88)

In article <302@Aragorn.dde.uucp> be@dde.uucp (Bjorn Engsig) writes:

>Let me start to comment on power with integer exponents.
>
>Pick up any first grade textbook on numerical analysis, and you will
>be told NEVER to use a power function like that.  First, if you need to
>calculate  x ** n (fortran notation), you will most often need
>x ** (n-1)  etc. as well, and it should be calculated using recursion,
....

Why do you think the compiler would generate n * log(x) for x^n where
n is an integer? The compiler knows that 'n' is an integer, and is
free to generate the most efficient code that it can -> including
iterative loops.


	x^n ==> {
		    tmp = x;
		    odd = 1;
		    if (n > 0) { 
			if (n & 1) {
			    odd = x;
			}
			while (n) {
			    tmp = tmp * tmp;
			    n = n >> 1;
			}
			return tmp * odd;
		    } else if (n < 0) {
			return (1/(x^-n));
		    } else { /* n == 0 */
			return 1.;
		    }
		}

this generates perfectly reasonable code (yes, it can be improved 8-)))
for x^n where n is an integer.

If n is known to be a constant, then the compiler can generate optimal code
for the integer power computation.

If you want x^r where r is a double or float, the compiler can generate
the appropriate log and exp calls....


So maybe you can elaborate on your difficulty with an exponentiation
operator in light of the surprising ability of compilers to generate
reasonable code.


John Danskin
decwrl!jmd

karl@haddock.ISC.COM (Karl Heuer) (01/20/88)

In article <302@Aragorn.dde.uucp> be@dde.uucp (Bjorn Engsig) writes:
>[why he believes a power operator is a bad idea, and apparently that
>exponentiation in general should be avoided]

I'm only concerned with integral exponents, since the floating-point case is
already covered by the standard function pow().

>If you need to calculate x ** n (fortran notation), you will most often need
>x ** (n-1) etc. as well

If you need to calculate x *^ n (proposed C notation), it is highly likely
that n is a small compile-time constant, and that x *^ (n-1) is not of
interest.

>... Thus: Power with integer exponent is not needed!

More precisely, *^ is not needed for the application you're thinking of.  But
it sure would be useful to be able to write (expr *^ 2) instead of the ugly
mess with temp variables that C currently requires.

Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint

nevin1@ihlpf.ATT.COM (00704A-Liber) (01/21/88)

In article <7139@brl-smoke.ARPA> gwyn@brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:

>
>If you do much geometric programming at all, you quickly realize
>that the squaring operator (expr ** 2) is quite heavily used.

(pointer to pointer to 2 is heavily used?? :-))  Yes, but if you know that you
are going to be squaring you can replace it with (expr * expr) (possibly
needing temp variables depending on the side effects concerning expr), or write
a macro to do it for you.
-- 
 _ __			NEVIN J. LIBER	..!ihnp4!ihlpf!nevin1	(312) 510-6194
' )  )				"The secret compartment of my ring I fill
 /  / _ , __o  ____		 with an Underdog super-energy pill."
/  (_</_\/ <__/ / <_	These are solely MY opinions, not AT&T's, blah blah blah

edw@IUS1.CS.CMU.EDU (Eddie Wyatt) (01/22/88)

> >
> >If you do much geometric programming at all, you quickly realize
> >that the squaring operator (expr ** 2) is quite heavily used.
> 
> (pointer to pointer to 2 is heavily used?? :-))  Yes, but if you know that you
> are going to be squaring you can replace it with (expr * expr) (possibly
> needing temp variables depending on the side effects concerning expr), or write
> a macro to do it for you.

  NO!!!! objection number 1.  You missed part of the point in the 
dicussions about adding power which is having a infixed notation
for the operator (we program in C here not Lisp :-)). BTW there exist
a nice notation for pointers to pointers, **.

  Objection number 2,  about the use of macros :  you may find that
macros don't cut it and here's why.  Consider the macro definition
for square :

		#define sqr(x)		((x)*(x))

used in the context of the macro :

		#define distance_2(x1,y1,x2,y2)   \
			  sqrt((double) sqr((x1)-(x2)) + sqr((y1)-(y2)))

The expressions ((x1) - (x2)) and ((y1) - (y2)) are evaluated twice.
That means instead of the 2 multiplications, 2 subtractions, 1 addition
and 1 subroutine call that the computation seems to need, it does 2 multi,
4 SUBS, 1 add, and 1 subroutine - two more floating point operations!  
This gets even worst if x1, y1, x2 or y2 are expressions themselves.
Note the point being made for the second time is that macros
can have so very subtle side effects.

-- 

Eddie Wyatt 				e-mail: edw@ius1.cs.cmu.edu

gwyn@brl-smoke.ARPA (Doug Gwyn ) (01/23/88)

In article <3461@ihlpf.ATT.COM> nevin1@ihlpf.UUCP (00704A-Liber,N.) writes:
>Yes, but if you know that you are going to be squaring you can replace it
>with (expr * expr) (possibly needing temp variables depending on the side
>effects concerning expr), or write a macro to do it for you.

Gee, thanks, I didn't realize that..

I guess I could also punch holes appropriately in the paper tape for my
Turing machine.

eao@anumb.UUCP (e.a.olson) (01/23/88)

In article <3461@ihlpf.ATT.COM> nevin1@ihlpf.UUCP (00704A-Liber,N.) writes:
>In article <7139@brl-smoke.ARPA> gwyn@brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:
>
>>
>>If you do much geometric programming at all, you quickly realize
>>that the squaring operator (expr ** 2) is quite heavily used.
>
>(pointer to pointer to 2 is heavily used?? :-))  

    Yeah, you see, when they design these geometric machines they
    take this into consideration and treat the location 2 as 'special' -
    when you use a pointer that points to anything pointing to it (or
    anywhere near it, within reason [ except 0, q.v. ]),
    the last location you referenced is automatically squared.  Any
    arithmetic overflow is propagated out thru the carry bit into
    location 0.  ;^()

varol@cwi.nl (Varol Akman) (01/25/88)

In article <302@Aragorn.dde.uucp> be@dde.uucp (Bjorn Engsig) writes:
>
> [various points against power function]
>

A programmer likes to have anything that is conceptually easy to have
under his/her thumb.  To me any language without power function is only
a toy for wimps.

nevin1@ihlpf.ATT.COM (00704a-Liber) (01/28/88)

In article <698@PT.CS.CMU.EDU> edw@IUS1.CS.CMU.EDU (Eddie Wyatt) writes:
.I wrote (put some credits in :-)):
.> are going to be squaring you can replace it with (expr * expr) (possibly
.> needing temp variables depending on the side effects concerning expr), or write
.> a macro to do it for you.
.
.  NO!!!! objection number 1.  You missed part of the point in the 
.dicussions about adding power which is having a infixed notation
.for the operator (we program in C here not Lisp :-)).

Then where is the operator for string concatenation, and square root, and
everything other binary function that is used by C programmers?  If you want a
method added to C for inserting infix functions (something I do not want) then
say so; but, the normal way to add functions to C is with prefix notation.

.  Objection number 2,  about the use of macros :  you may find that
.macros don't cut it and here's why.  Consider the macro definition
.for square :
.
.		#define sqr(x)		((x)*(x))
.
.used in the context of the macro :
.
.		#define distance_2(x1,y1,x2,y2)   \
.			  sqrt((double) sqr((x1)-(x2)) + sqr((y1)-(y2)))
.
.The expressions ((x1) - (x2)) and ((y1) - (y2)) are evaluated twice.
.That means instead of the 2 multiplications, 2 subtractions, 1 addition
.and 1 subroutine call that the computation seems to need, it does 2 multi,
.4 SUBS, 1 add, and 1 subroutine - two more floating point operations!  
.This gets even worst if x1, y1, x2 or y2 are expressions themselves.
.Note the point being made for the second time is that macros
.can have so very subtle side effects.

Let me rephrase objection number 2:  Here is a bad macro for defining squaring.
Since the macro given doesn't work in all cases, a power operator should be
added to C.  [This is my opinion of objection #2]

This is not good enough reasoning in my book!  As I suggested before, you need
temp variables to get this macro right!  Don't add features to the language
just because some programmers don't know how to get it right!
-- 
 _ __			NEVIN J. LIBER	..!ihnp4!ihlpf!nevin1	(312) 510-6194
' )  )				"The secret compartment of my ring I fill
 /  / _ , __o  ____		 with an Underdog super-energy pill."
/  (_</_\/ <__/ / <_	These are solely MY opinions, not AT&T's, blah blah blah

reggie@pdn.UUCP (George W. Leach) (01/28/88)

In article <175@piring.cwi.nl> varol@cwi.nl (Varol Akman) writes:

>A programmer likes to have anything that is conceptually easy to have
>under his/her thumb.  To me any language without power function is only
>a toy for wimps.


      Better watch yourself!  There are still many macho assembly programmers
out there and they have your number :-)



-- 
George W. Leach					Paradyne Corporation
{gatech,rutgers,attmail}!codas!pdn!reggie	Mail stop LF-207
Phone: (813) 530-2376				P.O. Box 2826
						Largo, FL  34649-2826

edw@IUS1.CS.CMU.EDU (Eddie Wyatt) (01/28/88)

In article <3521@ihlpf.ATT.COM>, nevin1@ihlpf.ATT.COM (00704a-Liber) writes:
> 
> Then where is the operator for string concatenation, and square root, and
> everything other binary function that is used by C programmers? 

Why not? why not have an extendable language, where the user is free to 
define his own infix operators?  Is it that outragous?  
THIS IS JUST HYPOTHETICAL - I"M NOT SERIOUSLY APPROSING THIS!


> .		#define sqr(x)		((x)*(x))

> Let me rephrase objection number 2:  Here is a bad macro for defining squaring.
> Since the macro given doesn't work in all cases, a power operator should be
> added to C.  [This is my opinion of objection #2]

   No this is not my objection.  My objection is that even in cases that
the macro does evaluate the correct value with no adverse side effects,
there are other subtilties.  Which is in this case the amount of work needed
to calcuated the square.

> 
> This is not good enough reasoning in my book!  As I suggested before, you need
> temp variables to get this macro right!  Don't add features to the language
> just because some programmers don't know how to get it right!

  	I know that the macro won't work in all situations, I don't think you
can write one that will work in all situations.  So o.k. I'm game, what's
"the right" way to write the macro.  :-/  

-- 

Eddie Wyatt 				e-mail: edw@ius1.cs.cmu.edu

dsill@NSWC-OAS.arpa (Dave Sill) (01/29/88)

In article <175@piring.cwi.nl> Varol Akman <varol@cwi.nl> writes:
>A programmer likes to have anything that is conceptually easy to have
>under his/her thumb.  To me any language without power function is only
>a toy for wimps.

[Assuming "operator" was meant, not "function".]

If you can specify a power operator that makes everyone happy, then
fine, do it.

You'll need to define the operator itself, the assignment form of the
operator, the precedence of the operator, the semantics of the
operator including the types it operates on (float, int,
positive/negative), range, domain, et cetera.  From the discussion
recently on this topic it should be clear that most of us don't have
this "under our thumbs".

Meanwhile leave us wimps and our toy language alone.

=========
The opinions expressed above are mine.

How much work would a network work if a network could net work?

decot@hpisod2.HP.COM (Dave Decot) (01/30/88)

> Why not? why not have an extendable language, where the user is free to 
> define his own infix operators?  Is it that outragous?  
> THIS IS JUST HYPOTHETICAL - I"M NOT SERIOUSLY APPROSING THIS!

What does "APPROSING" mean?  Is that one of your own user-defined infix
operators?  I'm afraid I don't have any documentation for this extension:
I couldn't find it in the "standard" dictionaries.

:-)

Dave Decot
hpda!decot

ned@ghostwheel.UUCP (Ned Nowotny) (02/06/88)

In article <744@PT.CS.CMU.EDU> edw@IUS1.CS.CMU.EDU (Eddie Wyatt) writes:
>In article <3521@ihlpf.ATT.COM>, nevin1@ihlpf.ATT.COM (00704a-Liber) writes:
>> 
>> Then where is the operator for string concatenation, and square root, and
>> everything other binary function that is used by C programmers? 
>
>Why not? why not have an extendable language, where the user is free to 
>define his own infix operators?  Is it that outragous?  
>THIS IS JUST HYPOTHETICAL - I"M NOT SERIOUSLY APPROSING THIS!
>

In some sense, C++ has this (mis-)feature -- operator and function overloading.

Conceptually, overloading is very nice.  It allows programmers to declare new
data types and operations on them using standard notations.  For instance, a
complex double data type can be defined and then operations can be defined on
these data types using the "+", "-", etc. operators.

Unfortunately, not all programmers seem to agree on what constitutes a good
use of operator overloading.  I have seen code which overloaded "+" and "-"
to add and remove, respectively, an object from a set of objects.  The result
was an unforeseen side effect to some global data structure using these
operators on the given data type and code similar to the following:

do_something();
A + B;
do_something_else();

That's right.  It looks like a useless expression, but its not.  Its just a
headache for the next programmer.  Function overloading can result in similar,
but less painful abuses.

Of course, it can be argued that the misuse of a feature by a programmer is
no excuse for blaming the feature.  However, functional notation is perfectly
adequate for programmer defined operations and somewhat easier to track down.
Infix notation is better left to a language implementor.  At least then,
everyone who uses the language knows what a given expression means, even
when it doesn't mean the right thing.

-- 

Ned Nowotny (ned@ghostwheel.aca.mcc.com.UUCP)

chip@ateng.UUCP (Chip Salzenberg) (02/12/88)

In article <132@ghostwheel.UUCP> ned@ghostwheel.aca.mcc.com.UUCP (Ned Nowotny) writes:
>In article <744@PT.CS.CMU.EDU> edw@IUS1.CS.CMU.EDU (Eddie Wyatt) writes:
>>Why not? why not have an extendable language, where the user is free to 
>>define his own infix operators?
>
>In some sense, C++ has this (mis-)feature -- operator and function overloading.
>
>Unfortunately, not all programmers seem to agree on what constitutes a good
>use of operator overloading.  I have seen code which overloaded "+" and "-"
>to add and remove, respectively, an object from a set of objects.
>
>do_something();
>A + B;
>do_something_else();
>
>That's right.  It looks like a useless expression, but its not.

And I have seen code where "read()" writes and "write()" reads.  So what?

The programmer should have defined "+=" instead of "+".  So fire the
programmer; don't hobble the other programmers by restricting their
power of expression.

>Of course, it can be argued that the misuse of a feature by a programmer is
>no excuse for blaming the feature.

I couldn't agree more.  :-|

-- 
Chip Salzenberg                 UUCP: "{codas,uunet}!ateng!chip"
A T Engineering                 My employer's opinions are a trade secret.
       "Anything that works is better than anything that doesn't."