# Pre calculate mathematical expressions in Fortran 90

Is there some flag to let the Fortran compiler pre calculate a math expression before compiling it?. I have to write expressions that contain many small 4x4 matrix multiplications. The thing is, most of the elements of these small 4x4 matrices are zero, so in terms of performance it's better to actually do the multiplication manually and write down the resulting expression, that way you eliminate the unnecessary multiplications by 0. Doing this is error prone, and I thought that compiler optimizations like -O3 would take care of this but they don't. I read about tools like symPy and matlab that let you write expressions, manipulate and simplify them and generate the code for Fortran or C, but if there is some compiler flag for this would be even better.

• Do you know where the zeros are? If so, you can do the symbolic computations in systems like Maple or Mathematica that has the simplifications already done, and then let them generate Fortran or C code. Jul 27 '14 at 16:52
• Oh yes, that was one alternative I was aware of. A cheaper approach could be SymPy (I didn't use it yet but I'll give it a try) where you can also do the symbolic manipulation and simplification, then generate a C or Fortran code with codegen, or just naively copy-paste the result and clean it. I was hoping there was some way other than external tools, but I guess Fortran simply doesn't have symbolic computations like more advanced languages like Matlab and Maple. Jul 27 '14 at 17:18
• Yeah, probably SymPy is the best --- let us know if you run into any problems with it or if it can't do what you need. Jul 28 '14 at 3:58
• "Doing this is error-prone" -- that's why you have tests, right? Aug 1 '14 at 17:09