質問

Is there a built-in way to calculate the correctly rounded n-th root of a Python 3 decimal object?

役に立ちましたか?

解決

According to the documentation, there is a function power(x,y) :

With two arguments, compute x**y. If x is negative then y must be integral. The result will be inexact unless y is integral and the result is finite and can be expressed exactly in ‘precision’ digits. The result should always be correctly rounded, using the rounding mode of the current thread’s context

This implies that power(x, 1.0/n) should give you what you want.

You can also take the nth root with

nthRoot = Decimal(x) ** (Decimal(1.0) / Decimal(n) )

Not sure if you consider either of these "built in" as you have to compute the reciprocal of n explicitly to get the nth root.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top