I want to use this rational number in computations without losing the accuracy of the picture in Matlab:
f = 359.0 + 16241/16250.0
I think storing, for instance by f = uint64(359.0 + 16241/16250.0)
loses accuracy, seen as 360 in Matlab.
I think the best way to handle the thing is never to store the value but to store its factors like
% f = a + b/c
a = 359
b = 16241
c = 16250
and then doing computation by the variables a, b and c, and giving the result as a picture.
Is this a good way to maintain the accuracy?
Perhaps create a
Rational
class and define the needed operations (plus
,minus
,times
,etc.). Start with something like this:Rational.m
Examples
Construct objects:
Add and subtract:
Multiply and divide:
Get decimal value:
Extension to chappjc's answer.
I have now
I run it
How can you multiply in this class the double with Rational?
Extension to LuisMendo's answer
I got this as the error for your suggestion by py
which is more than the proposed error storing error above.
I run in WolframAlpha
and get
I am not sure if this is what you meant in your comment of your answer.
As you suggest, if you absolutely don't want to lose accuracy when storing a rational number, the best solution probably is to store the number in terms of its integer components.
Instead of your three components (
f = a + b/c
) you can reduce the reprentation to two components:f = n/d
. Thus each rational number would be defined (and stored) as the two-component integer vector[n d]
. For example, the numberf
in your example corresponds ton=5849991
andd=16250
.To simplify handling rational numbers stored this way, you could define a helper function which converts from the
[n d]
representation ton/d
before applyling the desired operation:Then
If you want to achieve arbitrarily high precision in computations, you should consider using variable-precision arithmetic (
vpa
) with string arguments. With that approach you get to specify how many digits you want: