Fraction类的构造函数和from_float在Python中有什么区别?

huangapple go评论68阅读模式
英文:

what is the difference between the Fraction class constructor and from_float in Python

问题

我使用类构造函数Fraction来创建分数。
在使用Fraction类构造函数和from_float方法创建浮点数转分数时,有什么区别吗?

我使用不同的数字进行了测试,结果是相同的。
例如:

from fractions import Fraction

f1 = Fraction(0.3)
f2 = Fraction.from_float(0.3)

print(f1) # 输出:5404319552844595/18014398509481984
print(f2) # 输出:5404319552844595/18014398509481984

英文:

I am using the class constructor Fraction to create fractions.
What is the difference between using the Fraction class constructor and from_float method when creating fractions from floating-point numbers?

I tested it with different numbers and I got same answers.
for instance:

from fractions import Fraction

f1 = Fraction(0.3)
f2 = Fraction.from_float(0.3)

print(f1)  # Output: 5404319552844595/18014398509481984
print(f2)  # Output: 5404319552844595/18014398509481984

答案1

得分: 1

来自文档

从版本3.2开始更改: Fraction 构造函数现在接受 floatdecimal.Decimal 实例。

注意: 从Python 3.2开始,您还可以直接从 float 构造一个 Fraction 实例。

换句话说,在Python版本小于3.2时,您必须使用 Fraction.from_float 来从 float 构造一个 Fraction。自3.2版本以后,这已经不再需要,但可能仍然存在,以免破坏向后兼容性。您还可以使用它来进行更明确的类型检查,因为如果传递其他类型,Fraction.from_float 将引发错误,而 Fraction 构造函数可能会默默接受并潜在导致微妙的错误。

英文:

From the documentation:

> Changed in version 3.2: The Fraction constructor now accepts float and decimal.Decimal instances.

> Note: From Python 3.2 onwards, you can also construct a Fraction instance directly from a float.

In other words, in Python < 3.2, you had to use Fraction.from_float to construct a Fraction from a float. Since 3.2 this has become unnecessary, but still exists probably so as not to break backwards compatibility. You may also want to use it for more explicit type checking, as Fraction.from_float would raise an error if you passed some other type, which the Fraction constructor might silently accept and potentially lead to subtle bugs.

答案2

得分: 1

I will provide the translation for the code-related text:

阅读实现,您可以看到在类型检查后,函数from_float 通过调用 as_integer_ratio 方法获取分子和分母,就像Fraction(float)一样。

英文:

Reading the implementation you can see that after type checking, the function from_float gets numerator and denominator with the same method as Fraction(float) does.
That is, by calling as_integer_ratio.

huangapple
  • 本文由 发表于 2023年4月11日 16:22:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75983817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定