分数 #

对于分数的计算,math.js 支持 Fraction 数据类型。分数支持由 fraction.js 提供支持。与 数字大数字 不同,分数可以存储具有无限循环小数的数字,例如 1/3 = 0.3333333...,可以表示为 0.(3),或者 2/7 可以表示为 0.(285714)

用法 #

可以使用 fraction 函数创建分数。

math.fraction('1/3')   // Fraction, 1/3
math.fraction(2, 3)    // Fraction, 2/3
math.fraction('0.(3)') // Fraction, 1/3

并且可以像这样在 addmultiply 等函数中使用:

math.add(math.fraction('1/3'), math.fraction('1/6'))      // Fraction, 1/2
math.multiply(math.fraction('1/4'), math.fraction('1/2')) // Fraction, 1/8

请注意,并非所有函数都支持分数。例如,三角函数不支持分数。当不支持时,函数会将输入转换为数字并返回一个数字作为结果。

大多数函数将根据输入的类型确定输出的类型:输入为数字则输出为数字,输入为分数则输出为分数。无法根据输入确定输出类型的函数(例如 math.evaluate)将使用默认数字类型 number,这可以在实例化 math.js 时进行配置。为了默认使用分数而不是 数字,请像这样配置 math.js:

// Configure the default type of number: 'number' (default), 'BigNumber', or 'Fraction'
math.config({
  number: 'Fraction'
})

// use the expression parser
math.evaluate('0.32 + 0.08') // Fraction, 2/5

支持 #

以下函数支持分数:

转换 #

分数可以通过 numberfraction 函数进行转换。将分数转换为数字时,如果该值无法用 16 位数字表示,可能会丢失精度。

// converting numbers and fractions
const a = math.number(0.3)                       // number, 0.3
const b = math.fraction(a)                       // Fraction, 3/10
const c = math.number(b)                         // number, 0.3

// loosing precision when converting to number: a fraction can represent
// a number with an infinite number of repeating decimals, a number just
// stores about 16 digits and cuts consecutive digits.
const d = math.fraction('2/5')                   // Fraction, 2/5
const e = math.number(d)                         // number, 0.4
Fork me on GitHub