0

I read that Fortran has strict rules on the order in which expressions are evaluated. For some numerical algorithm, this is very important.

How do numerical C programs control the order of floating point operations and prevent the compiler from "optimizing" to an undesirable order of operations such as changing (a*b)*c to a*(b*c).

user782220
  • 10,677
  • 21
  • 72
  • 135
  • My bet is that they don't, because standard prevents compiler from reordering of floating point operations, since it can change behaviour of the program. But someone with a standard under their hand is needed. – luk32 Jan 16 '14 at 07:57
  • And if I understand right, this is even true for Fortran: http://stackoverflow.com/questions/13135262/consistent-floating-point-arithmetic-in-fortran-with-different-compilers-on-diff ; Where did you read the statement about those strict rules? – Andreas Fester Jan 16 '14 at 07:58
  • 2
    If you're not happy with [the standard rules](http://en.cppreference.com/w/c/language/operator_precedence), put specific expressions inside parentheses. But in general, the compiler will only reorder if if can 100% say that a sub-expression is without side-effects. – Some programmer dude Jan 16 '14 at 07:58
  • 2
    This is a very broad question. As @JoachimPileborg said, the answer is within the standard. However, if you face a specific problem, feel free to edit the post and add more detail/code. – Michael Foukarakis Jan 16 '14 at 08:00
  • 3
    Fortran allows a compiler to transform an arithmetic expression into a mathematically equivalent expression, but this equivalence is based on the the mathematics of real numbers not of floating-point numbers. So a Fortran compiler might transform an expression based on the assumption of associativity which is not true for f-p arithmetic. – High Performance Mark Jan 16 '14 at 08:17
  • @HighPerformanceMark -- I'd expect parenthesis must be obeyed even if algebraically superfluous.. right? – agentp Jan 17 '14 at 14:03
  • 2
    @george: for C and C++ right, for Fortran, not necessarily. See http://software.intel.com/sites/default/files/article/164389/fp-consistency-122712_1.pdf for instance. – High Performance Mark Jan 17 '14 at 14:12
  • nice, what that doc says is the standard requires obeying parenthesis, but intel by default does not strictly follow the standard. – agentp Jan 18 '14 at 14:02

2 Answers2

0

Using parenthesis ensures the order of execution.

egur
  • 7,830
  • 2
  • 27
  • 47
0

I believe it doesn't optimize the code as this could lead to undesirable results. What it usually does is take the numerical expression infix notation and then convert it into postfix by applying stack operations based on the priority of different operators.
this is done note to optimise the code but to simply increase the readability of the code by omitting all the parenthesis and then rearranging based on the priority.
. priority order

krish
  • 104
  • 1
  • 13