Link to home
Start Free TrialLog in
Avatar of panaz
panaz

asked on

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.
Avatar of ozo
ozo
Flag of United States of America image

(FLT_EPSILON + FLT_EPSILON) + 2
FLT_EPSILON + (FLT_EPSILON + 2)


FLT_MAX * (FLT_MAX * FLT_MIN)
(FLT_MAX * FLT_MAX) * FLT_MIN
Avatar of panaz
panaz

ASKER

FLT_EPSILON : is this a standard global constant in C/ C++?
(FLT_EPSILON + 2.5) + -2.5  
FLT_EPSILON + (2.5 + -2.5)
FLT_EPSILON is in
#include <float.h>
Avatar of panaz

ASKER

thanks
Avatar of panaz

ASKER

#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


Avatar of panaz

ASKER

a and b have the same values here. looks like it dont work?
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;
Avatar of panaz

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of panaz

ASKER

okay
Avatar of panaz

ASKER

#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