date arithmetic - multiplication of doubles variables -


a question saw , didn't quite understand.

first create arbitrary values:

int x = random(); int y = random(); int z = random(); 

(int 32 bits) continue with:

double dx = (double) x; double dy = (double) y; double dz = (double) z; 

(double 64 bits)

the question tell if next statements always true (returns 1) or not.

a. dx+dy+dz==dz+dy+dx  b. dx*dy*dz==dz*dy*dx 

the answer (a) "yes, within range of exact representation double's" (so, or not always true? , if not always true, example of 3 values dx, dy, dz returns 0)

the answer (b) "no, e.g dx=tmax, dy=tmax-1, dz=tmax-2" tried , turned out same result (but i'm wrong :-/ )

i understand why answers correct

thanks!

in floating point arithmetic, should never test equality. classic example 0.1 + 0.2 != 0.3. (see http://0.30000000000000004.com/ more information, particularly see if language hides you. has nice explanation of how arises because 0.1 , 0.3 can't represented in doubles.) floating-point values should instead checked see if they're close enough each other in range, called "tolerance".

see ieee 754 definition: https://en.wikipedia.org/wiki/double-precision_floating-point_format

i disagree answer (a), because it's meaningless specify can "exactly represented" double - if every input double representation of given random bits (x, y, z), is, definition exact representation. plus, it's dubious "yes, under conditions" answer "is always true?" answer in case "no".

one counterexample (a) below. constructed considering floating point numbers have relative precision, adding small number large 1 may make no difference. make small number large enough, , will.

  • 1e16 + 1 + 1 = 10000000000000000
  • 1 + 1 + 1e16 = 10000000000000002

as (b), first thing randomly tried counterexample:

  • 0.1 * 0.1 * 0.7 = 0.007000000000000001
  • 0.7 * 0.1 * 0.1 = 0.006999999999999999

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -