With the current implementation of the class Fixed, b2TimeOfImpact() is not guaranteed to converge. Specifically, given the "right" input, the root finder will enter a cycle and never exit its loop.
This is caused by the fact that multiplication of Fixed objects is defined as follows:
(It should be noted that right shifting negative values is an implementation-defined operation. From a pragmatic standpoint this is not the problem, however, since you can probably assume any target platform has a two's complement architecture.)
This multiplication operator is used in the following expression in the root finder (secant method portion):
When all differences are small numbers, we run into trouble caused by the fact that the right shift operator rounds towards negative infinity, and not towards zero.
Suppose for simplicity that we have -eps * eps / eps where eps is the smallest possible fixed point number (represented internally by the integer 1). The multiplication then becomes (-1 * 1) >> BP, which results in -1 (or -eps). We then have -eps / eps left which becomes -1.0, not -eps as one might have expected.
I would suggest that the multiplication of Fixed objects is defined using integer division instead:
While integer division is also implementation-defined, it is much more likely to round towards zero. Alternatively, the root finder must be changed somehow.
This is caused by the fact that multiplication of Fixed objects is defined as follows:
Code: Select all
Fixed(RAW, (int)( ((long long)g * (long long)a.g ) >> BP));(It should be noted that right shifting negative values is an implementation-defined operation. From a pragmatic standpoint this is not the problem, however, since you can probably assume any target platform has a two's complement architecture.)
This multiplication operator is used in the following expression in the root finder (secant method portion):
Code: Select all
x = x1 + (target - f1) * (x2 - x1) / (f2 - f1);When all differences are small numbers, we run into trouble caused by the fact that the right shift operator rounds towards negative infinity, and not towards zero.
Suppose for simplicity that we have -eps * eps / eps where eps is the smallest possible fixed point number (represented internally by the integer 1). The multiplication then becomes (-1 * 1) >> BP, which results in -1 (or -eps). We then have -eps / eps left which becomes -1.0, not -eps as one might have expected.
I would suggest that the multiplication of Fixed objects is defined using integer division instead:
Code: Select all
Fixed(RAW, (int)( ((long long)g * (long long)a.g ) / (1 << BP)));While integer division is also implementation-defined, it is much more likely to round towards zero. Alternatively, the root finder must be changed somehow.