BenMorel
BenMorel

Reputation: 36544

How to check if a division with bcdiv() will produce a finite result?

I'm building a class for working with arbitrary precision decimal numbers in PHP, using the BCMath library internally.

When adding, subtracting, or multiplying two numbers, it is possible to forecast the required precision to be sure not to lose any digit.

However when it comes to division, the number of digits can be infinite, and I'd like my library to throw an exception if the result of the division cannot be represented as a finite number of digits.

How can I know, before dividing, if the result will be finite, and in that case, compute the scale of the result?

Upvotes: 0

Views: 553

Answers (2)

lhf
lhf

Reputation: 72332

A reduced fraction has a finite decimal representation if the only prime factors of the denominator are 2 and 5.

Using BCMath, I guess you'd have to implement the Euclidean algorithm for reducing a fraction to lowest terms and then test the denominator. It does not seem worth the trouble.

Upvotes: 0

kirilloid
kirilloid

Reputation: 14304

You need to perform % (modulus) operation... wait. Oh, SH...

Actually it is not possible w/o performing division (or similar steps) itself.

I may advice you to create a divmod function, which will return result of integer division (i.e. rounded down) and remainder. And check the remainder is equal to zero.

Also any rational number may be represented as repeating decimal, like 1/3 = 0.(3) and 1/7 = 0.(142857). The bad part is that period length may be up to value of this number, hence it's better to represent number as n/m internally if one wants to perform exact calculations with rational numbers.

Upvotes: 1

Related Questions