可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,
visit the help center for guidance.
Closed 7 years ago.
I know this is a bit hypothetical but I am wondering why no language I know does it.
For example, you want to store 1/3. Give the programmer an option to specify it as 1/3, and store 1 and 3. Something like
struct float {
int numerator;
int denominator;
};
Rational number arithmetic becomes really easy and considerably more accurate!
This would solve so many problems related to the precision and storage limitations of floating point numbers, and I dont see it introducing any new problems as well!
Hence my question: Why aren't rational numbers implemented and stored as fractions with zero loss of information?
As Joe asked, and others might also point out, I do not mean this to replace existing system, but to complement it.
Q: How do you store pi
?
A: So many times, I am just storing 1/3
and not pi
. pi
can be stored the old way, and 1/3
in the new way.
回答1:
The reason they are not stored this way by default is that the range of valid values that can fit in a fixed set of bits is smaller. Your float
class can store numbers between 1/MAXINT and MAXINT (plus or minus). A C/C++ float
can represent numbers between 1E+37 and 1E-37 (plus or minus). In other words, a standard float
can represent values 26 orders of magnitude bigger and 26 orders of magnitude smaller then yours despite taking half the number of bits. In general, it's more convenient to be able to represent very large and very small values than to be perfectly precise. This is especially true since rounding tends to give us the right answers with small fractions like 1/3. In g++, the following gives 1:
std::cout << ((1.0/3.0) * 3.0) << std::endl;
Remember that types in C++ have a fixed size in bits. Thus a datatype in 32 bits has at most MAX_UINT values. If you change the way it is represented, you're just changing which values can be precisely represented, not increasing them. You can't cram more in, and thus can't be "more precise". You trade being able to represent 1/3 precisely for not being able to represent other values precisely, like 5.4235E+25.
It is true that your float
can represent values more precisely between 1E-9 and 1E+9 (assuming 32 bit ints) but at a cost of being completely unable to represent values outside of this range. Worse, while the standard float
always has 6 digits of precision, your float
would have precision that varied depending on how close to zero the values were. (And note that you are using twice the bits that float
does.)
(I'm assuming 32 bit int
s. Same argument applies for 64 bit int
s.)
Edit: Also note that most data people use float
s for is not precise anyway. If you are reading data off of a sensor, you've already got imprecision, so being about to "perfectly" represent the value is pointless. If you are using a float
in any sort of computing context, it's not going to matter. There is no point in perfectly describing '1/3' if your purpose is to display a bit of text 1/3rd of the way across the screen.
The only people who really need perfect precision are mathematicians, and they generally have software that gives them this. Very few others need precision beyond what double
gives.
回答2:
Real number arithmetic becomes really easy and considerably more accurate!
No, it doesn't. The struct you describe only handles rational numbers, i.e. those that can be expressed as fractions. The set of real numbers includes both rational and irrational numbers. Most real-world calculations are done using real numbers, so you can't just limit yourself to the rationals and expect everything to be fine.
I am wondering why no language I know does it.
Most of the languages that I can think of make it possible to do exactly what you describe. In C, you can create a struct that contains numerator and denominator, and you can define a bunch of functions that operate on such structs. C++ makes things a LOT easier by letting you define a class and operations on that class -- same idea, much nicer syntax, etc. In fact, different sets of numbers are often used as examples in OO languages: you might start by defining a Rational class, and then extend that to include Imaginary numbers, and so on.
I'd guess that the reason that there aren't more languages with built-in support for exact types probably has to do with the fact that processors don't directly support such operations. Modern processors include instructions that implement arithmetic operations for floating point types, so it's easy to include those in any language. Supporting exact types would mean building a math library into the language, and it's probably better on several levels to leave the math library out of the language and let those who need it build it into their software.
If you're going to go to all the trouble to produce exact results, you probably don't want to limit yourself just to rationals, so the struct you give as an example isn't going to cut it. Being able to do exact calculations on rationals isn't very helpful if you fall back to inexact results the first time an irrational number shows up. Fortunately, there are sophisticated math systems out there. Mathematica is one well-known example.
回答3:
C++ at least includes a compile time rational arithmetic library. Here's an example:
#include <ratio>
#include <iostream>
int main() {
using a = std::ratio<3,5>;
using b = std::ratio<7,6>;
using c = std::ratio_multiply<a,b>::type;
std::cout << c::num << '/' << c::den << '\n'; // prints 7/10
}
Here we multiply 3/5 by 7/6 and get 7/10.
回答4:
Strap on your helmets, because we're about to get theoretical up in here.
Any math undergrad could give you an elevator explanation of Cantor's proof of the uncountable cardinality of the real numbers. For a longer explanation, go here.
But as Caleb pointed out, the real number field contains both rational and irrational numbers. This means that some subset of the real number field will never be representable as a numerator/denominator pair. How big is this subset? As it turns out, most real numbers are irrational, because the set of rationals is countable.
Here's the punchline: Storing numbers in this way would be very silly because most outputs of real-valued functions cannot be stored as a numerator and a denominator.
This may seem hard to believe, but think about common transcendental functions, e.g. sin, cos, log. Most outputs of these functions aren't rational, and the guys who wrote IEEE 754 and other early FP stuff knew this. They figured that dealing with a small amount of error in exchange for the possibility of representing (with some truncation) a much larger portion of the real number field was a good design tradeoff.
回答5:
Many CPUs have special treatment for floating points (see Wikipedia) and the float
data type in the language ensures programs can utilize the FPU in an easy way. On the other hand I don't know of any CPU which can handle Fractions with special assembler instructions so fractions can easily and efficiently be implemented inside a library and don't have to be a language feature. If you want to use fractions in C++, you can use Boost.Rational.
The Reason why modern CPUs implement floating point arithmetic instead of handling fractions is that floating points can be implemented much more easily. To implement the basic float
operations you basically need to be able to add, subtract multiply and divide integers and do some bit shifting. To compare to fractions on the other hand you need to find the greatest common divisor of two ints, which is much harder to implement in hardware.
回答6:
Contrary to many of the answers you've gotten, your idea is good for many kinds of problems. Especially problems like this one in which you know that there will be a lot of cancelling, and want an exact answer. For this reason, Python has the fractions
module, and as @bames53 points out, C++ has <ratio>
.
回答7:
“Hence my question: Why aren't rational numbers implemented and stored as fractions with zero loss of information?”
The C++ standard library lacks many practically necessary types that other languages and libraries offer. The Boost library already offers a rational number implementation. And it appears that it may shortly also offer the proposed decimal types, e.g. for handling currency amounts.
As to why those types are lacking, the C++ standard library generally just provides bare bones general building blocks, not the more practically useful things that one would build with those blocks. I.e. it's minimalistic. The Boost library is just a tad less minimalistic, and then e.g. the Poco library is more like other languages’ more functionally rich standard libraries.
回答8:
There are a few reasons:
- No support from common architecture. This is understandable, since fraction must always comes with simplification. This is not trivial to be implemented at hardware level, or rather, it will be an instruction without much application.
- Cannot handle very big or very small numbers. Or BigInteger must involve. And for very big or very small numbers, we usually don't need most of the precision provided.
- If this is a type supported at the language level, it must support conversion with other numeric types. It must decide when to return floating type if the internal representation has fixed precision (in case of multiplication).
In a language, the decision to support something is usually decided by its application (or the rationale of the language). If the application is small, it has less chance to be supported.