`
13146489
  • 浏览: 252067 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Why we don’t use Doubles for Financial Calculations

    博客分类:
  • J2EE
阅读更多
原文地址:http://bloodredsun.com/?p=320
另一篇文章:What Every Computer Scientist Should Know About Floating-Point Arithmetichttp://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html


My current client is in the middle of hiring some Java developers and as I
mentioned earlier in March (Interviewing – the importance of PASSION!) I’ve been doing some of the interviewing. One of the things we’ve done is to create a technical task to see how the candidates actually code. It’s a simple exercise that requires them to think through some of the basics of financial operations and one thing that has surprised me has been the common use of doubles to represent financial values. It’s been highlighted for some time that this is not a great thing to do but someone actually challenged me to show that it wasn’t.

So here we go…

view plaincopy to clipboardprint?
package com.bloodredsun; 
 
public class DoubleOperation { 
 
    public static void main(String[] args) { 
 
        double t1 = 10.266d; 
        double t2 = 10.0d; 
 
        //Outputs 0.266 
        System.out.println(t1-t2); 
 
        double h1 = 100.266d; 
        double h2 = 100.0d; 
 
        //Outputs 0.26600000000000534 
        System.out.println(h1-h2); 
    } 

Ouch! That is not what we want but it is the classic behaviour of doubles. The inability to represent some decimals in the IEEE-754 format (as binary fractions) causes this. If we want correct precision the answer is to use BigDecimals but we have to remember to use Strings in the constructors or you end up with the same issues that you were trying to avoid.

view plaincopy to clipboardprint?
package com.bloodredsun; 
 
import java.math.BigDecimal; 
 
public class BigDecimalOperation { 
 
        public static void main(String[] args) { 
 
        BigDecimal t1 = new BigDecimal("10.266"); 
        BigDecimal t2 = new BigDecimal("10.0"); 
 
        //Outputs 0.266 
        System.out.println(t1.subtract(t2)); 
 
        BigDecimal h1 = new BigDecimal("100.266"); 
        BigDecimal h2 = new BigDecimal("100.0"); 
 
        //Outputs 0.266 
        System.out.println(h1.subtract(h2)); 
    } 

That’s great but wouldn’t it be nice to use the normal operators rather than the overly-verbose method calls for the mathematical operations.

Now there is no way that we can do this in Java but if we let ourselves use another language on the JVM…

view plaincopy to clipboardprint?
package com.bloodredsun 
 
object ScalaBigDecimalOperation { 
 
  def main (args: Array[String]) { 
    var t1 = BigDecimal("10.266") 
    var t2 = BigDecimal("10.0") 
    //Outputs 0.266 
    println(t1 - t2) 
 
    var h1 = BigDecimal("100.266") 
    var h2 = BigDecimal("100.0") 
    //Outputs 0.266 
    println(h1 - h2) 
  } 

Scala FTW!

PS if you want to know more about floating point operations have a read of What Every Computer Scientist Should Know About Floating-Point Arithmetic
分享到:
评论

相关推荐

    Android代码-Android练习UI

    We are going to use Dagger2 to replace production code with Test Doubles. We are going to practice pair programming. Getting started This repository contains an Android application to show Super ...

    test-doubles:测试双演示

    测试双打演示 测试替身的演示文稿和代码 开始使用代码 克隆回购 运行bundle install 运行rspec 演示文稿入门 克隆回购 运行./server ... 按 P 开始演示 ...麻省理工学院许可证 (MIT) 版权所有 (c) [2015] [弗兰克·...

    Go Web Programming(Manning,2016)

    You’ll learn how to implement the dependency injection design pattern for writing test doubles, use concurrency in web applications, and create and consume JSON and XML in web services. Along the ...

    Apache Hadoop 3.x state of the union and upgrade guidance

    Also, HDFS 3.0 announced GA for erasure coding, which doubles the storage efficiency of data and thus reduces the cost of storage for enterprise use cases. HDFS added support for multiple standby ...

    Go Web Programming(《Go Web 编程》英文版 作者:Sau Sheong Chang)

    You’ll learn how to implement the dependency injection design pattern for writing test doubles, use concurrency in web applications, and create and consume JSON and XML in web services. Along the ...

    对ObservableCollection的Doubles进行排序

    在.NET框架中,`ObservableCollection<T>`是一种常用的集合类,尤其在WPF和MVVM模式中,它允许我们在数据绑定时实时更新视图。当数据发生变化时,它会触发通知事件,使得UI能够自动更新。然而,对于包含可比较元素...

    php.ini-development

    Please see the actual settings later in the document for more details as to why ; we recommend these changes in PHP's behavior. ; display_errors ; Default Value: On ; Development Value: On ; ...

    英文原版-Go Web Programming 1st Edition

    You’ll learn to implement the dependency injection design sample for writing check doubles, use concurrency in net functions, and create and eat JSON and XML in net providers. Alongside...

    CRC Press - Cyber Forensics.7z

    We trust the material we have included will serve as a starting point for the many professionals who are beginning their journey into this exciting discipline. We begin our journey into the realm of ...

    Reengineering.NET.0321821459.epub

    leading .NET architect Bradley Irby introduces proven best practices for revitalizing older .NET code and integrating new architectural and development advances into business-critical systems that can...

    apache-maven-3.0.2-bin

    * [MNG-4941] - PluginDescriptorBuilder doesn't populate expression/default-value fields for mojo parameters * [MNG-4952] - [regression] RELEASE field of repository metadata is not updated upon ...

    Go Web Programming (PDF, EPUB, MOBI)

    You'll learn how to implement the dependency injection design pattern for writing test doubles, use concurrency in web applications, and create and consume JSON and XML in web services. Along the way...

    java英文笔试

    For the purpose of this document, we will focus on technical questions. #### 5. Please tell me about OOPs. **Answer**: OOPs stands for Object-Oriented Programming System. It is a programming ...

    3-14-find-doubles-RainerMauersberger23:3-14-find-doubles-RainerMauersberger23由GitHub Classroom创建

    w [0]返回w的第一个字母一旦找到双精度数,就无需继续for循环 概念 单元1,单元2,用于循环,列出。 如何完成这项作业 为了完成此分配,您将需要在main.py文件中编写代码。 完成后,该作业将自动进行测试并评分。 ...

Global site tag (gtag.js) - Google Analytics