Warning double to float

possible loss of data

Page 1 of 1

2 Replies - 719 Views - Last Post: 02 March 2009 - 10:41 AM Rate Topic: -----

#1 keli_k  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 16-January 09

Warning double to float

Posted 02 March 2009 - 10:12 AM

Hello;

I keep getting this warning when I compile my program. I have all variables involved declared as floats, is it because in the equations I am using ints?



void mstiff(float x, float e, float z, float ke[][4])
{ 
	ke[0][0] = 12*e*z/pow(x,3);
	ke[0][1] = 6*e*z/pow(x,2);
	ke[0][2] = -12*e*z/pow(x,3);
	ke[0][3] = 6*e*z/pow(x,2);
	ke[1][0] = 6*e*z/pow(x,2);
	ke[1][1] = 4*e*z/x;
	ke[1][2] = -6*e*z/pow(x,2);
	ke[1][3] = 2*e*z/x;
	ke[2][0] = -12*e*z/pow(x,3);
	ke[2][1] = -6*e*z/pow(x,2);
	ke[2][2] = 12*e*z/pow(x,3);
	ke[2][3] = -6*e*z/pow(x,2);
	ke[3][0] = 6*e*z/pow(x,2);
	ke[3][1] = 2*e*z/x;
	ke[3][2] = -6*e*z/pow(x,2);
	ke[3][3] = 4*e*z/x;
}




Can you tell me why I would be getting this warning?

Is This A Good Question/Topic? 0
  • +

#3 horace  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 290
  • View blog
  • Posts: 1,898
  • Joined: 25-October 06

Re: Warning double to float

Posted 02 March 2009 - 10:25 AM

if you are using C the pow() function returns a double result
http://www.cprogramm...om/fod/pow.html

the expression is therefore evaluated as double and it is when you assign this to the float variable you get the warning as you convert a high precision value to a lower precision

you can cast the result to remove the warning, e.g.
	ke[0][0] = (float) (12*e*z/pow(x,3));


This post has been edited by horace: 02 March 2009 - 10:39 AM

Was This Post Helpful? 1

#4 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5642
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: Warning double to float

Posted 02 March 2009 - 10:41 AM

Values like 12 and 3 are not explicit floats, they're implicit ints. This can cause problems.

You should be fine if you do:
ke[0][0] = 12.0 * e * z / pow(x,3.0);



Edit:

// this will not behave as desired; the int 12 will gank the equation
ke[0][0] = (float) (12*e*z/pow(x,3));

//For an explicit float cast, you want this:
ke[0][0] = ((float)12)*e*z/pow(x,(float)3);


This post has been edited by baavgai: 02 March 2009 - 10:42 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1