floating point addition and multiplication not necessarily associative.

(a) Give an example to show that floating point addition is not necessarily associative.
(b) Give an example to show that floating point multiplication is not necessarily associative.
Who is Participating?

x

Commented:
You changed
float a,b,c,d;
to
double a,b,c,d;
For doubles, use DBL_EPSILON instead of FLT_EPSILON
0

Commented:
(FLT_EPSILON + FLT_EPSILON) + 2
FLT_EPSILON + (FLT_EPSILON + 2)

FLT_MAX * (FLT_MAX * FLT_MIN)
(FLT_MAX * FLT_MAX) * FLT_MIN
0

Author Commented:
FLT_EPSILON : is this a standard global constant in C/ C++?
0

Commented:
(FLT_EPSILON + 2.5) + -2.5
FLT_EPSILON + (2.5 + -2.5)
0

Commented:
FLT_EPSILON is in
#include <float.h>
0

Author Commented:
thanks
0

Author Commented:
#include<float.h>
#include<iostream>

using namespace std;
int main()
{
float a,b,c,d;

a = (FLT_EPSILON + 2.5) + -2.5 ;
b = FLT_EPSILON + (2.5 + -2.5);

cout<<"a :"<<a<<endl;

cout<<"b :"<<b<<endl;

return 0;
}

csci>a.out
a :1.19209e-07
b :1.19209e-07

0

Author Commented:
a and b have the same values here. looks like it dont work?
0

Commented:
You are probably doing double precision arithmetic
try

a =  (FLT_EPSILON + 2.5);
cout<<"a :"<<a<<endl;
b = a + -2.5;
cout<<"b :"<<b<<endl;
c = 2.5;
d = -2.5;
a = (FLT_EPSILON + c) + d;
cout<<"a :"<<a<<endl;
b = (float)(FLT_EPSILON + 2.5) + -2.5;
cout<<"b :"<<b<<endl;
b =(FLT_EPSILON + 2.5f) + -2.5f;
cout<<"b :"<<b<<endl;
0

Author Commented:
I guess its still the same values:

int main()
{
double a,b,c,d;

a =  (FLT_EPSILON + 2.5);
cout<<"a :"<<a<<endl;
b = a + -2.5;
cout<<"b :"<<b<<endl;
c = 2.5;
d = -2.5;
a = (FLT_EPSILON + c) + d;
cout<<"a :"<<a<<endl;

b = (float)(FLT_EPSILON + 2.5) + -2.5;
cout<<"b :"<<b<<endl;

b =(FLT_EPSILON + 2.5f) + -2.5f;
cout<<"b :"<<b<<endl;

return 0;

}

[ Wrote 28 lines ]

csci>g++ test.cpp
csci>a.out
a :2.5
b :1.19209e-07
a :1.19209e-07
b :0
b :0
0

Author Commented:
okay
0

Author Commented:
#include<float.h>
#include<iostream>
#include<limits>

using namespace std;

int main()
{
float a,b,c,d;

a =  (FLT_EPSILON + 2.5);
cout<<"a :"<<a<<endl;
b = a + -2.5;
cout<<"b :"<<b<<endl;

c = 2.5;
d = -2.5;
a = (FLT_EPSILON + c) + d;
cout<<"a :"<<a<<endl;

b = (float)(FLT_EPSILON + 2.5) + -2.5;
cout<<"b :"<<b<<endl;

b =(FLT_EPSILON + 2.5f) + -2.5f;
cout<<"b :"<<b<<endl;

return 0;

}

csci>g++ test.cpp
csci>a.out
a :2.5
b :0
a :0
b :0
b :0
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.