سؤال

I'm looking at binary data representations for fractions, and I was wondering what kind of a data structure the fraction would have if you were to store both the numerator and denominator that store a fraction. Is it just two separate numbers that have no relation but are combined when used in a calculation?

هل كانت مفيدة؟

المحلول

If you want to store rational numbers without losing precision the correct way is to store both the numerator and denominator.

In practice most people use either floating-point math or built-in/library arbitrary-precision number data-types (e.g. Java's BigDecimal).

If you specifically want to use a data-type for fractions, some languages have built-in types for rational numbers. For most other languages there is usually a library with a usable datatype (e.g. for Java Apache Commons has a Fraction class and for C/C++ GMP has a mpq_t datatype)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top