MATLAB: Does the generated code from a Data Type Conversion block avoid using division in Real-Time Workshop 7.1 (R2008a)

Embedded Coder

The attached model uses a Data Type Conversion block to convert fixed-point scaling. The following code is expected to be generated:
dtc_test001_Y.Out1 = dtc_test001_U.In1 / 10U;
However, the code is generated as follows:
dtc_test001_Y.Out1 = (uint16_T)((uint32_T)dtc_test001_U.In1 * 52429UL >> 19);

Best Answer

This enhancement has been incorporated in Release 2009b (R2009b). For previous product releases, read below for any possible workarounds:
The option to force the Data Type Conversion block to use division in the generated code is not available with Real-Time Workshop Embedded Coder 5.1 (R2008a). By design, multiplication is preferred over division under the assumption that division is very costly (slow) and should be avoided.
Even if division were an option, there would be numerical pitfalls that would have to be very carefully avoided.
This is illustrated in the following example:
uint32_T u = 524288;
y1 = (uint32_T)(u / 10U);
y2 = (uint32_T)(((uint64_T)u * 52429UL) >> 19);
y1 = 524288
y2 = 524289
If these pitfalls were not avoided, there would be violations of the design rule of bit-true agreement between Simulink and RTW for fixed-point calculations.
To ensure bit true agreement, the design of Simulink and RTW is such that simulation and code generation always agree with each other.