文本版|topic 高级搜索
   名人堂 帮助 论坛制度 意见反馈 | 首页 博客 周新贴 专题 求职 读书
RSS 底部
 
社区导航: 专家门诊   网络技术   操作系统   数据库   程序设计   系统应用   考试认证   CIO及信息化   站长交流   综合交流   下载基地  51CTO产品服务 设为首页 | 收藏本站
51CTO技术论坛» Java » Why some unwanted result comes out in floating-point operation?       [ 打印]  [ 订阅]  [ 收藏]  [ 推荐给朋友]   [ 本帖文本页]

论坛跳转:
     
标题: [转载] Why some unwanted result comes out in floating-point operation?  ( 查看:147  回复:0 )   
 
ddgff
新新人类  点击可查看详细



帖子 17
精华 0
无忧币 5007
积分 85
阅读权限 20
注册日期 2008-2-13
最后登录 2008-4-19 离线

[查看资料]  [发短消息]  [Blog
       
发表于:2008-4-7 14:47   标题:Why some unwanted result comes out in floating-point operation?
上一帖 |
See a question in Java基础, copy my own article here written quite while ago.

Q. When I do floating-point operation, why some unwanted result comes out?

// Example, why do the digits 000000000003 extra after 20.255 come out?
double x = 27.475;
double y = 7.22;
System.out.println(x - y); // 20.255000000000003

A: That is a famous floating-point phenomenon. Your number is represented in decimal, and your computer represents them in binary, some discrepancy will happen with that conversion back-and-forth. It is normal since Machine Language / Assembly / Fortran time. If you go to an interview, someone ask you this question, you don't know the answer, and inexperienced programmer situation will be exposed to the interviewer immediately.

When you output, format it to what you desired.

How the precision changed? Explanation is no easy job.
You need understand what is radix.

Radix for decimal is 10
Radix for binary is 2

29.3 in decimal is actually
2 * 101 + 9 * 100 + 3 * 10-1
In binary
11101.010011001.............
Do the same thing, but replace 10 to 2.

However, the number will never end. You will find out something is short in decimal may become infinite long in binary. And the opposite will not be infinite long, but possible longer then the computer system allowed. Computer cannot allow infinite long number, it must be truncated to fit the precision of the floating-point number in the system.

Therefore, the value of some floating-point number changes in the conversion from one radix to another radix back-and-forth.

If 29.125 in decimal is converted to binary, there are no problems. It will be 11101.001 in binary precisely, since 0.125 is 2-3 or 1/8.



网络虽虚拟,技术无边界,来看看大家“真面目”!
2008-4-7 14:471楼
[ 顶部 ]
     
论坛跳转:  

| | |

标记已读 · 删除论坛Cookies · 文本版 · WAP
 
| 诚征版主 | 版主堂 | 意见建议 | 大史记 | 论坛地图
Copyright©2005-2008 51CTO.COM  Powered by Discuz!
本论坛言论纯属发布者个人意见,不代表51CTO网站立场!如有疑义,请与管理员联系。
京ICP备05051492号