I have found out that matlab symbolic toolbox automatically converts numbers into fractions. this is OK for short terms but for the complicated ones, this may result in longer terms and also higher computational costs.
lets describe it with a simple example:
syms x
a=0.1; % a is double
b=a*x;
results:
b=
x/10
but I don't want Matlab to convert results in this format is there any way to make matlab stop doing this?
(I don't want to use vpa
to convert the result again).
As per the documentation for sym
, the default conversion method for numeric values is rational approximation/representation, the 'r'
flag. If you want to use decimal approximation/representation, then you'll need to directly specify that. However, care should be taken in how you do this, as the following example illustrates:
syms x
b1 = sym(0.1,'d')*x
b2 = sym('0.1')*x
which returns
b1 =
0.10000000000000000555111512312578*x
b2 =
0.1*x
As you know, many floating-point decimal values are not exact. sym(0.1,'d')
uses the floating-point value of 0.1
to length digits
. Matlab has probably chosen the other method as the default because the representation is not easily confused with floating-point.
If you want a more automatic way of converting floating point values to "exact" decimal representations with sym
, you might try something like this:
syms x
a = 1e-26;
b1 = sym(a,'d')*x
b2 = sym(sprintf('%g',a))*x
which returns
b1 =
0.000000000000000000000000010000000000000000384948697491918*x
b2 =
0.00000000000000000000000001*x
However, I'm not sure what you have against vpa
as it is actually a much cleaner way to do this: b1 = vpa(a)*x
or b1 = vpa(a*x)
.