`
13146489
  • 浏览: 245898 次
  • 性别: 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
分享到:
评论

相关推荐

    Test-Driven JavaScript Development

    I’ll use unit tests to show you how the language behaves, and we’ll take the opportunity to let tests drive us through the implementation of some helper utilities, which we’ll use throughout Part ...

    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 ...

    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 ; ...

    对ObservableCollection的Doubles进行排序

    您可以看一下:如何对可观察的集合进行排序?[^]对ObservableCollection(React性扩展)的值进行排序[^]

    英文原版-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 ...

    Testing with F#(PACKT,2015)

    Starting with an introduction to the concepts behind test automation, you will learn how to set up your test environment for unit testing and how to execute your test suite within and outside 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 ...

    Developer.Testing.Building.Quality.into.Software

    In Developer Testing, leading test expert and mentor Alexander Tarlinder presents concise, focused guidance for making new and legacy code far more testable. Tarlinder helps you answer questions like:...

    通过具有宇宙学常数的Drinfel'd doubles向(3 + 1)方向引力

    我们介绍了(2 + 1)(Anti)-de Sitter和PoincaréLie代数的量子变形的(3 + 1)维,它与(2 + 1)的Chern-Simons公式所施加的条件兼容 )引力。 由于这种兼容性是由Drinfel'd双重结构产生的变形自动实现的,因此...

    Go.Web.Programming

    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...

    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...

    Mockito Cookbook - Packt

    Mockito is a testing framework that allows you to easily create test doubles (mocks) of the system under test's collaborators. You can use mocks to better simulate the behavioral patterns of your ...

    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