Juergen VonHagen wrote (little bits snipped for brevity):: >robin wrote: >> >> > From: Aleksandar Donev <[log in to unmask]> >> >> > I have a pedagological question for the Fortran teachers out there. Variants of this are not only useful for teachers, but also practitioners. >> > How does one write "best" an expression with mixed types, say: >> > >> > complex(kind=sp) :: x,y >> > integer :: k >> > >> > y=(k-1)/(k+1)*x If k is positive, the first part (integer arithmetic) is always 0, so y is 0 If k is zero, y = -x If k is negative (except -1), y = 2.*x This assumes left to right evaluation, so (k+1)/(k-1) is integer arithmetic. I believe this is part of the standard, but would bow to RM's better knowledge. If it is not, I have screwed up big time over many years, but my vendors seem to believe what I do. >> > I recommend to students to explicitly write all the type conversions: >> > >> > y=cmplx(k-1,0,sp)/cmplx(k+1,0,sp)*x Losing track of who wrote what, but the below y = x*(k-1)/(k+1) should work well. A complex multiplied by a real and divided by a real. The above is overly complex (stupid pun). Do our compiler writers realise that that expression is real/real*complex, or does their code go through all the aggravation of complex(real,0)/complex(real,0)*complex? Interested to hear, especially from SL who works for my vendor. I have just re-written two routines in one of my applications where an ex-colleague went overboard in a similar fashion. My re-writes to real arithmetic seem to have reduced size and CPU (but so minimally that it's hard to judge the latter). >> > though >> > >> > y=x*(k-1)/(k+1) >> > >> > also works. >> >> Only by accident. And it's not efficient, either. No, it doesn't work by accident. It works because of the left/right evaluation and because evaluation is done with the highest precision. Efficiency is another story, see above. >> One must always be careful about writing division involving integers. >> (k-1)/(k+1) can easily return a zero result, especially wen it's written at >the >> start of an expression (as is your first example). >> >> Writing REAL(k+1) is sufficient in your example. >> Converting to complex is wasteful, and is almost unreadable. >> It's wasteful because two complex multiplications are introduced >> when simple scalar multiplication by a complex value is all that's required. > >how about writing > >(k-1.)/(k+1.) Agreed with the double chevron comment (Robin?). The last code (if integer is faster than real -- not always true these days) could be inferior to REAL(K+1)/(k-1). Regards, Paddy Paddy O'Brien, Transmission Development, TransGrid, PO Box A1000, Sydney South, NSW 2000, Australia Tel: +61 2 9284-3063 Fax: +61 2 9284-3050 Email: [log in to unmask] Either "\'" or "\s" (to escape the apostrophe) seems to work for most people, but that little whizz-bang apostrophe gives me little spam. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%