On Thu, 22 Nov 2007 12:50:38 -0800 (PST), kostas <sk******@gmail .com>

wrote in comp.lang.c++:

Hi

I was asked to propose an interview question for C/C++ programmers

(CAD/CAE software)

I came up with the following

In the other comments category:

----------------------------------------------------------------------------------------

float fun(float value)

{

float f1 =0., f2 = value;

Superfluous '.' on initializer.

float tol = value/1000.;

Superfluous and possible dangerous '.' on "1000.". If you had left

off the decimal point, the constant would be of type int and would be

directly promoted to float. With the decimal point, you have a

constant of type double, causing value to be promoted to double, the

division done to produce a double result, that double result then

being converted back to float by the assignment to "tol".

A division by a power of ten, which does not have an exact

representation in most binary floating point formats, can produce

different results when performed in double versus when performed in

float. The final float could actually have a different value when the

division is performed on doubles and converted to a float.

float result,tmp;

while(1) {

result = (f2+f1)/2.;

Ditto again on the "2.", although since 1/2 is exactly representable

in most binary floating point formats the difference is likely to be

negligible. Again, though, you are performing a float addition of f1

and f2, converting the result to double to divide by (double)2.0, then

converting the double result back to float for the assignment.

tmp = result*result-value;

if(fabs(tmp)<=t ol)

break;

if(tmp>0.) {

One more time, "0." forces the float value "tmp" to be converted to

double, although a compiler might optimize this one away, converting

it to: "if (!tmp)"

f2 = result;

}else {

f1 = result;

}

}

return result;

}

CAD and CAE programs should probably never use float, as the lowered

precision compared to double is often intolerable in complex

calculations. A good experienced engineering programmer should

actually complain about the extra execution time and possible accuracy

implications of the forced conversions caused by mixing double

literals with float values.

Using "1000." is not a good idea when mixing with floating point types

other than double. You should have used 1000F, or omitted the decimal

point to produce an integer literal, allowing the compiler to handle

it automatically and properly.

--

Jack Klein

Home:

http://JK-Technology.Com
FAQs for

comp.lang.c

http://c-faq.com/
comp.lang.c++

http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++

http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html