laozian mao
laozian mao

Reputation: 75

Exact fraction arithmetic without Matlab converting to decimal representation?

So suppose I want to compute 1/9+1/13 in exact fraction form. Since both numbers are rational, an exact result in fraction form is possible. But when I type 1/9+1/13 in Matlab, the result is always a decimal approximation.

How do I obtain exact fractional form?

Upvotes: 2

Views: 1634

Answers (1)

horchler
horchler

Reputation: 18484

Matlab is primarily a numeric environment and thus uses floating-point numbers by default. Generally, you'll need to use the Symbolic Math toolbox for something like what you describe. In the case of your example:

sym('1/9')+sym('1/13')

returns 22/117.

Alternatively, you could try the rats (rational fraction approximation) function that works with floating point inputs:

rats(1/9+1/13)

returns the string '22/117'. There's also rat that returns the numerator and denominator as separate floating point outputs.

[n,d] = rat(1/9+1/13)

returns 22 and 117 for n and d, respectively.

Upvotes: 5

Related Questions