6

I'm porting some code over from Processing to Java, and one issue I've come across is that processing's precompiler turns any doubles to floats. In Eclipse however, I've had to explicitly cast my values as float. Still though, I get errors that I don't understand. For instance, shouldn't putting an f at the end of this statement fix the type mismatch (Type mismatch: cannot convert from double to float)?

    springing[n] = .05*(.17*(n+1))f; 

And even on simpler statements like this I get a type mismatch. What am I doing wrong?

  float theta = .01f;
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
Mike
  • 963
  • 4
  • 16
  • 38
  • Do you in fact need to use floats, or could your program run as well (with some more memory usage and more precise results) with double? This might be easier :-) – Paŭlo Ebermann Feb 23 '11 at 01:41
  • I'm still unclear on the difference between doubles and floats. Is there a page that explains this? – Mike Feb 23 '11 at 01:51
  • a float is a 32-bit single-precision floating-point value, a double is 64-bit double-precision, see http://en.wikipedia.org/wiki/Floating_point – Jesper Feb 23 '11 at 02:57

3 Answers3

12

Well, your second statement is correct by Java's standards, but in your first example Java is probably trying to prevent you from converting doubles to floats due to a loss of precision that must be explicitly asked for by the programmer, as so:

double a = //some double;
float b = (float) a;  //b will lose some of a's precision
donnyton
  • 5,874
  • 9
  • 42
  • 60
1

According the Java grammar, the f suffix is only applicable to float literals. Your second statement should work. The first however is an expression and therefore requires a cast:

springing[n] = (float)(.05*(.17*(n+1)));
Bryan Kyle
  • 13,361
  • 4
  • 40
  • 45
1

In your first example, the f suffix is only valid directly on literals, not after a whole expression. So write it in either of those ways (assuming springing is a float[]):

springing[n] = .05f*(.17f*(n+1)); 
springing[n] = (float)( .05*(.17*(n+1)));

The first does the whole calculation (apart from the n+1 part) in float, the second one calculates in double and then converts only the result to float.

(And in both cases, the parenthesis between .05 and .17 (and the matching one) is usually superfluous, since multiplication is associative. It might do some difference for really big values of n, but in these cases you would usually want the other way to avoid overflow.)

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210