python精确运算_如何在Python中使用精确的浮点运算?

I'm having this issue in python with float arithmetic.

The equation I'm solving goes as follows:

-a *((x-m)*110.0*(1-m))**b +a*((x-m)*110.0*(1-m))**c

a is a really large positive number (in the hundred thousands)

b is 1.0000002

c is 0.9999998

When I do this in excel I get accurate results but when I do it in python I get completely inaccurate results.

The results are exactly the same for each separate part until I multiply by -a and a.

So ((x-m)110.0(1-m))**b and ((x-m)110.0(1-m))**c are exactly the same as their excel calculated values but when they're multiplied by the large number they completely change.

How do I do this? do I have to use a different language? Is this problem only in python or is it in all languages?

Edit: It is the exact same equation in excel as in python. Exactly the same. The numbers are also the same until I multiply by a and -a. then they are both off by 5 point something. The answer in excel is around 0.47 for x=0.5 and m = 0.265 while the answer for python is around -0.67

解决方案

It is quite hard to understand what precision you are looking for but i think that you can also take a look at the decimal module. -

It offers several advantages over the

float datatype:

Decimal “is based on a floating-point

model which was designed with people

in mind, and necessarily has a

paramount guiding principle –

computers must provide an arithmetic

that works in the same way as the

arithmetic that people learn at

school.” – excerpt from the decimal

arithmetic specification.

Decimal numbers can be represented

exactly. In contrast, numbers like 1.1

and 2.2 do not have an exact

representations in binary floating

point. End users typically would not

expect 1.1 + 2.2 to display as

3.3000000000000003 as it does with binary floating point.

The exactness carries over into

arithmetic. In decimal floating point,

0.1 + 0.1 + 0.1 - 0.3 is exactly equal to zero. In binary floating point, the

result is 5.5511151231257827e-017.

While near to zero, the differences

prevent reliable equality testing and

differences can accumulate. For this

reason, decimal is preferred in

accounting applications which have

strict equality invariants.

The decimal module incorporates a

notion of significant places so that

1.30 + 1.20 is 2.50. The trailing zero is kept to indicate significance. This

is the customary presentation for

monetary applications. For

multiplication, the “schoolbook”

approach uses all the figures in the

multiplicands. For instance, 1.3 * 1.2

gives 1.56 while 1.30 * 1.20 gives

1.5600.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值