Why does adding parentheses alter the result of this Scala expression?

I am porting some code to Scala, which makes extensive use of floating point arithmetic. I wrote the following code in Scala based on copy / paste version of C:

val complimentaryTerms = 2640.96e-6 * sin (f5) + 63.52e-6 * sin (2.0 * f5) + 11.75e-6 * sin (2.0 * f3 - 2.0 * f4 + 3.0 * f5) + 11.21e-6 * sin (2.0 * f3 - 2.0 * f4 + f5) - 4.55e-6 * sin (2.0 * f3 - 2.0 * f4 + 2.0 * f5) + 2.02e-6 * sin (2.0 * f3 + 3.0 * f5) + 1.98e-6 * sin (2.0 * f3 + f5) - 1.72e-6 * sin (3.0 * f5) - 0.87e-6 * t * sin (f5) 

The result of this calculation is a little from what version C produces. However, if I enclose the expression in parentheses, for example:

 val complimentaryTerms = (2640.96e-6 * sin (f5) + 63.52e-6 * sin (2.0 * f5) + 11.75e-6 * sin (2.0 * f3 - 2.0 * f4 + 3.0 * f5) + 11.21e-6 * sin (2.0 * f3 - 2.0 * f4 + f5) - 4.55e-6 * sin (2.0 * f3 - 2.0 * f4 + 2.0 * f5) + 2.02e-6 * sin (2.0 * f3 + 3.0 * f5) + 1.98e-6 * sin (2.0 * f3 + f5) - 1.72e-6 * sin (3.0 * f5) - 0.87e-6 * t * sin (f5)) 

the resulting value exactly matches version C. It seems the order of operations should be different when there are parentheses or not, but I don't understand why this matters. Any idea what is going on here?

+8
scala
source share
1 answer

This is because of the output of the semicolon. Example ( //; is a valid semicolon):

 val x = 1 //; + 1 //; println(x) // 1 

And with parentheses:

 val x = (1 + 1) //; println(x) // 2 

Or with the tail "+":

 val x = 1 + 1 //; println(x) // 2 

Semicolon Output Rules
The end of a line is treated as a semicolon if one of the following conditions is not met:

  • The line in question ends with a word that would not be legal as the end of an instruction, such as a period or infix operator.

  • The next line begins with a word that the statement cannot run.

  • The line ends in brackets (...) or brackets [...] because they cannot contain multiple operators.

+14
source share

All Articles