Monday, November 30, 2020

Difference between Simulink model and executable results

When you generate code from a Simulink model, build an executable and compare the results of Simulink model and excutable, you will usually notice that there are differences. To make sure that these differences are normal, do the following:

  1. Verify that Simulink and executable inputs are exactly (up to 16 digits) the same. Use format long before printing Simulink inputs and outputs. Do the same for executable input and output printing. Most of the time, differences in results are due to differences in significant digits. Pro Tip: If your Simulink model uses constant blocks for all inputs, when you generate C code, those inputs will be embedded into the code. If you build this code and don't touch any of the inputs, you can be sure that Simulink and executable inputs are the same without doing anything extra.
  2. In the executable main(), use double (64bit floating point) data type for inputs and outputs.
  3. Run the executable two times and verify that results of these two runs are exactly the same. If they are not, this is possibly due to a random number generator in model. Add random seed to input so that same random numbers will be generated which then guarantees consecutive run results being the same.
  4. Build executable as 32bit, run and save results. Build as 64bit, run and save results. Compare 32bit and 64bit results. The difference in these results will give you an idea of difference order of magnitude to expect.
  5. Verify that the difference between Simulink run and executable run is of similar order of magnitude to the difference between 32bit and 64bit runs.

Letters to a novice programmer

Previous letter

When the problem you need to solve has only two states, don't create a monster (e.g. FizzBuzz Enterprise), with state machine builders, polymorphism and templates sprinkled around! Use simple switch statements so that a developer can easily move through code with ctrl+left clicks, without ever needing to use ctrl+F.