Trouble with doubles (adding, setting precision)

Firstly,
I have a loop that adds 0.3 three times. For some reason it comes out as .8999999999999!
Why is this?
Second, does anyone know where I can download a class or view source code that allows you to set decimal precision of a double? I started writing one myself but it's more complex than I thought and I'd rather just use someone elses if I could...

The precision of calculations and how numerical
floating point numbers are handled in computers are is
very relevant for business situations. Actually the
problems with decimal numbers themselves often need to
be understood by those creating the business rules (ie
like the sales people, audit departements, CEOs, etc.)
The precision of the java double itself is unlikely to
ever have an impact on that though.
For example, if a business person asks you to
calculate a mortgage payement then they must
understand exactly the impact that the imprecision of
such decimal calculations will have on the business.
And they must understand it enough so that they can
decide the correct way for handling it. The rules
for handling this case, at least in the
mortgage/banking industry, is going to be far less
the possible precision that a java double can have.
(The reason of course being that how this is handled
d impacts the credits of the lender and the debits of
the lendee.)
Given the above it matters little what data types are
used to handle the calculation itself. But rather
that the calculation is done in such a way that the
business people understand it and that they understand
the limitations of it as well.Okay, I don't disagree with any of that. Still not sure about your overall point though.
* P-L said "don't add doubles in a loop because it compounds rounding errors."
* I said "but if the number of addtions multiplied by the maximum error is still within your error tolerance, it's okay." In other words, Java's double's precision is not necessarily going to be a problem.
* You said some things that seem to agree with that final point, but your "that is fine if your job consists of nothing but evaluating computers, but for the rest of us the errors in the data that we are using..." comment makes it sound like you're disagreeing with my point: "The errors in Java's double may not cause you problems. Know it's limitations, and how they relate to your requirements."
Are you looking for an argument, now that "one exit point" has fizzled? :-) Or am I just being particularly dense today?
¶

Similar Messages

  • Having trouble with double entries in ical after installing Lion.  After entering an event, another one pops up right next to it.

    Having trouble with double entries in ical after installing Lion.  After entering an event, another one pops up right next to it.

    Check iCal preferences, the Accounts Tab. You might have duplicate accounts.

  • Trouble with double

    Hi all,
    I tried to compile and run this code :
    public class TestDouble {
         public static void main(String ar[]) {
              //The total balance
              double balance =19620.9d;
            balance -= 3542.9d;
            //Expecting the balance to be 16078
              System.out.println("Remaining balance : "+balance);
              balance -= 6144.0d;
              //Expecting the balance to be 9934
              System.out.println("Remaining balance : "+balance);
              balance -= 1200.0d;
              //Expecting the balance to be 8734
              System.out.println("Remaining balance : "+balance);
              balance -= 1200.0d;
              //Expecting the balance to be 7534
              System.out.println("Remaining balance : "+balance);
              balance -= 5134.0d;
              //Expecting the balance to be 2400
              System.out.println("Remaining balance : "+balance);
              balance -= 1200.0d;
              //Expecting the balance to be 1200
              System.out.println("Remaining balance : "+balance);
              balance -= 1200.0d;
              //Expecting the balance to be 0
              System.out.println("Remaining balance : "+balance);
              System.out.println("Remaining balance > 0 : "+(balance>0));
    }I expect the final balance to be printed as zero.
    However this is the out put that I am getting
    G:\Ws\Test>javac -version
    javac 1.6.0_14
    G:\Ws\Test>javac G:\Ws\Test\TestDouble.java
    G:\Ws\Test>java -version
    java version "1.6.0_15"
    Java(TM) SE Runtime Environment (build 1.6.0_15-b03)
    Java HotSpot(TM) Client VM (build 14.1-b02, mixed mode, sharing)
    G:\Ws\Test>java TestDouble
    Remaining balance : 16078.000000000002
    Remaining balance : 9934.000000000002
    Remaining balance : 8734.000000000002
    Remaining balance : 7534.000000000002
    Remaining balance : 2400.000000000002
    Remaining balance : 1200.0000000000018
    Remaining balance : 1.8189894035458565E-12
    Remaining balance > 0 : trueCan someone help me in understanding what's wrong.
    Thanks,
    Anil

    For accounting, the thought of using rounding is not acceptable. Accounting typical only requires add, substract and multiplied by a quantity. An alternative to BigDecimal is to use long values for the smallest unit. e.g. use cents instead of dollars. The risk of error is important and BigDecimal is likely to be the best choice for this reason.
    However in finance or banking, rounding is better understood as it is used, often unavoidable. You will find double is typically used for simplicity (often speed is also given as justification) While double is dramatically faster than BigDecimal, this speed improvement is usually not required IMHO.
    Only large amounts of money are likely to have a significant rounding error, however large amounts of money are typically estimates. The problem with double is its limited precision, however money is a limit resource and very rare do you need more than 12 digits of accuracy. (double has 15-16 digits of accuracy) Even the US national debt can be represented to the cent using double, yet this is just an estimate. If you attempted to add up all the amounts involved in the US national debt, it would change while you are doing it.
    I worked at a bank where in one dept the unexplained PnL was measuring in "millions of pounds per month" (PnL being Profit and Loss) I can assure you if you has mentioned an error 1.8e-12 dollars it would be given a proportionate amount of consideration, if not amusement.
    In summary: There is no realistic, hard amount of money that would get an error using double which could not be handled by appropriate rounding. Any estimate of money is not accurate enough to require more precision than double.
    Edited by: Peter__Lawrey on 13-Dec-2009 14:38

  • Officejet Pro 8600 plus: trouble with double sided printing

    I have just installed Officejet Pro 8600 plus. My iMac is running on OS X 10.9.2
    I want to print a double sided brochure. And I have succeeded. However, the printing on one side of the paper is upside down.
    To achieve this:
    Print <Copies & Pages <Layout - turn on two-sided - long edge binding
    Layout direction is greyed out
    How can I fix this please

    Hello xxzz,
    Welcome to the HP Forums.
    I see that the flip on long edge option is greyed out for you when you try to print double sided. I will try to help you with this.
    Usually if an option is greyed out, it indicates that the software wasn't installed completely or correctly. That or the printer isn't capable of the task. Knowing that this printer is able to duplex, it could be a problem with the software/drivers.
    Try the following.
    Uninstall the software.
    Reset the print system.
    Verify/Repair disk permissions
    Re-install the software - software download
    Test to see if you're now able to choose the options.
    Let me know how things go, thank you for posting on the HP Forums.
    I worked on behalf of HP.

  • Trouble with national character set - HELP!

    I've got a problem with croatian characters like :h, f, , , p. They can not be displayed in Portal.
    There is no matter if it is display name or label...

    I think you've got me closer to the problem, whatever it is:
    [lars@laptop ~]$ xterm
    Warning: locale not supported by Xlib, locale set to C
    [lars@laptop ~]$ xterm -u8
    Warning: locale not supported by Xlib, locale set to C
    [lars@laptop ~]$ uxterm
    Warning: locale not supported by Xlib, locale set to C
    At least it seems to indicate a problem with the locale, which might be causing my problem - I don't know...
    [lars@laptop ~]$ locale
    LANG=en_DK.utf8
    LC_CTYPE="en_DK.utf8"
    LC_NUMERIC="en_DK.utf8"
    LC_TIME="en_DK.utf8"
    LC_COLLATE=C
    LC_MONETARY="en_DK.utf8"
    LC_MESSAGES="en_DK.utf8"
    LC_PAPER="en_DK.utf8"
    LC_NAME="en_DK.utf8"
    LC_ADDRESS="en_DK.utf8"
    LC_TELEPHONE="en_DK.utf8"
    LC_MEASUREMENT="en_DK.utf8"
    LC_IDENTIFICATION="en_DK.utf8"
    LC_ALL=

  • Trouble with double byte swapping routine

    I'm working on a program that reads little endian doubles from a DataInputStream and then swaps them. Usually, everything works fine. However, certain values don't swap correctly.
    I'm at a total loss as to why this is happening, so I hoped one of you guys could show me. I've included a demonstration program with the method I'm using to swap doubles.
    public class SwapTest
         public static void main(String[] args)
              new SwapTest();
         public SwapTest()
              // The swap routine works well with this value
              double d = 0.8660252094218776d;
              System.out.println("d before being swapped: " + d);
              // Swap to small order, then back to big order
              d = swapBytes(d);
              d = swapBytes(d);
              System.out.println("d after being swapped: " + d);
              System.out.println();
              // Everything gets totally hosed with this value
              d = 0.8660252079425844d;
              System.out.println("d before being swapped: " + d);
              // Swap to small order, then back to big order
              d = swapBytes(d);
              d = swapBytes(d);
              System.out.println("d after being swapped: " + d);
         private static double swapBytes(double sm)
              long smallendian = Double.doubleToLongBits(sm);
              long result;
              long l1 = (smallendian & 0x00000000000000FFL) << 56;
              long l2 = (smallendian & 0x000000000000FF00L) << 40;
              long l3 = (smallendian & 0x0000000000FF0000L) << 24;
              long l4 = (smallendian & 0x00000000FF000000L) << 8;
              long l5 = (smallendian & 0x000000FF00000000L) >>> 8;
              long l6 = (smallendian & 0x0000FF0000000000L) >>> 24;
              long l7 = (smallendian & 0x00FF000000000000L) >>> 40;
              long l8 = (smallendian & 0xFF00000000000000L) >>> 56;
              result = l1 | l2 | l3 | l4 | l5 | l6 | l7 | l8;
              return Double.longBitsToDouble(result);
    }

    The doubleToLongBits() method converts invalid values to NAN before converting

  • HT201342 What is the mail server for iCloud users? I lost all my emails, trouble with email account set-up.

    I lost all me emails, what is mail set-up? Mail.me.com?

    Incoming is imap.mail.me.com.  Outgoing is smtp.mail.me.com (see http://support.apple.com/kb/HT4864).  But if you're setting up iCloud mail on OS X Lion or higher, you go to Settings>iCloud and check Mail.  This will add the account with the proper settings.

  • Trouble with Menu Color Set

    The highlighted color on my Menus is very flaky, almost unreadible. Has anyone had problems here?
    The preview is ok on the PC but on the Blu-Ray player its a problem.

    Roy,
    What color did you choose, and what is the color that the Sub-picture Highlight appears over?
    In Encore, you can change the Color Set of your Sub-picture Highlights.
    Now, this term, "flaky," makes me wonder if what you are seeing is the limitation of a Sub-picture Highlight. It can only be 2-bit color - either ON, or OFF, and that means no feather, or anti-aliasing. Sub-picture Highlights will look "rough," and that is the nature of their limitation. Also, the Sub-picture Highlight will appear on top of all Button elements, when selected. Can you define what you mean by "flaky," and perhaps post a screen-cap of your Sub-picture Highlight?
    Good luck,
    Hunt

  • Trouble with audio midi set up new aggregate device

    hello im alex, im using apogee duet with logic and live, sorry for the mistakes , i am italian.
    a guy from ableton suggest me to create a new aggregate device made by apogee out and built in out put together in order to have a pre in the headphones
    THE PROBLEM : after create a new aggregate device , when i check the boxes to select inputs and outputs, the boxes stay empty, unchecked.
    (sometime i see flash of the window opening but after a millisecond desapperead)
    somebody can tell me something good to resolve ? thank u
    alex

    I'm having this same problem. Makes no difference which devices are selected, it isn't possible to create a new aggregate device with any devices at all, internal or external. 10.5.8 Audio MIDI setup 2.2.2
    Message was edited by: audiobiscuit

  • I am having trouble with iCloud

    I am having trouble with ICloud adding songs to my computer.  The only playlist that they show up in is "recently added".  They will not show up in the library or any other playlists even if I try to move them.  I am on a PC with Win7 Pro.

    Try to meka a manual backup.
    Settings>iCloud>Storage and Backup>Backup now.

  • I recently added my old mac hard drive to a new macbook with an SSD as my main OSX drive.  I am having trouble with permissions in viewing my old hard drive.  What is the best way to get complete access to my old hd installed in my new Macbook?

    I recently added my old mac hard drive to a new macbook with an SSD as my main OSX drive. I am having trouble with permissions in viewing my old hard drive, when I save a permission when I reboot the full access is changed again .  What is the best way to get complete access to my old hd installed in my new Macbook?

    Open the Get Info window for the old drive. Click the Lock icon on the bottom of that window and type in your password. In the permissions area click the Plus sign ( + ) and Add your Username to it and set it to Read & Write. Close that window. you should now have full access to all the files.

  • HT2404 Since downloading the new operating system on my iPhone 4S, I'm having trouble with my phone messaging.  I enter a number or input a number from my contacts and send my msg.  I then get error messagings showing a set of "1" are entered before my nu

    Since downloading the new operating system on my iPhone 4S, I'm having trouble with my phone messaging.  I enter a number or input a number from my contacts and send my message.  I then receive a error message stating the message can't be sent and it shows a set of "1s" were added in front of the number I entered.  Ex: 1 (1) xxx-xxx-xxxx.  Does anyone know why this is happening and how I can fix it?

    I realize this. When calling prepaid cus service it only gives you the option to input your #. If you dont the system hangs up on you. When I input my number the system doesnt recognize it and hangs up on me.

  • Trouble with DNS set up

    Hello !
    I've got a real trouble with my dns configuration... and i can't understand! so, i need some help....
    well, qutie newbie in mac os server, i run in on a G4, and i had not noticed any trouble until i've decided to run open directory as a master with LDAP, wanting to have a kerberos protection for the users.
    Kerberos doesn't want to play with me !
    I've been in console mode to have a look, and, actually i've seen this :
    "Oct 17 11:31:08 wakan servermgrd: servermgr_dns: no name available via DNS for 192.168.0.109
    Oct 17 11:31:08 wakan servermgrd: servermgr_dns: no reverse DNS entry for server, various services may not function properly"
    Ok... my DNS has a trouble... but i don't know how to fix it ! Is there anybody in this world who can help me?
    I don't want to have a real DNS for my little server... but i understand that my config is not good. I can understand that having a caching DNS can improve the quality of my config, and, in other hand that it is necessary for having the services of OSX server in an effeciant way, but i don't know the way and the parameters i've to put in my config to fix it.
    Now, just some words on my config...
    First, i've got an adress provided by my FAI (the frenchy workd for ISP, i think) is "193.252.209.135". This adress is set on a d-link modem router via PPOE. The DNS of my provider (wanadoo.fr) are 80.10.246.1 and 80.10.246.132.
    After this there is my G4 With mac osX server.
    • en0, the "extenal gate" and the internal ethernet on the computer is plug on the modem with the adress "192.168.0.109". the router is set on "192.168.0.1". the dns are 80.10.246.1 and 80.10.246.132.
    • en1, the "internal gate" for the network, an PCI card in the computer, has the parameters : adress "192.168.3.1", subnet "255.255.255.0", router "192.168.3.1". no dns records. (no VPN service for the moment). After this, i've a switch for the macs behind the server. (without any link agregation)
    All those parameters have been set by the gateaway assistant.
    And now the parameters inside the admin server :
    DHCP : en1 - adress from 192.168.3.2 to 192.168.3.254, name 192.168.3. no static card. Router 192.168.3.1. No name for domaine by defaut, name servers 80.10.246.1 and 80.10.246.132 No LDAP, no WINS.
    DNS : No zone transfert, recursivity is ON. No zone records.
    NAT : set on full, Transfert and Network Address Translation.
    When i've been on the terminal, i had those information:
    "wakan:~ st$ sudo changeip -checkhostname
    Password:
    Primary address = 192.168.0.109
    Current HostName = wakan.local
    The DNS hostname is not available, please repair DNS and re-run this tool."
    All my "main" services are working fine (AFP, Firewall, DHCP, DNS, Update) Open Directory is running without Kerberos. By the way, all the macs after the G4server can have a corect access to internet, and share information via LDAP of Open Directory, but i've to say that, a couple of days later, a friend of mine, who has a PC computer, can't have a DHCP dynamic address when he plug on my little network. I think that it is an other trouble, and i've decided to have e look to this later... but if someone knows how to resolve it...
    So here begins the nightmare for me... so if anybody can help me... i realy need some help to fix this mystery!!!
    Special thanks!

    As the router modem is already doing NAT why use NAT in the server?
    If you want to use OpenDirectory and other services you should/need to set up the DNS correctly using the server's private IP (and others in the same range the server is setup with). The domainname used internally can be different than your public one.
    And then use the server as the only DNS for you LAN clients and the server itself. Forwarders (your ISP DNSes) in /etc/named.conf usually speeds up lookups of external addresses (also turning off IPv6 can help that too).

  • I am an iPad novice and whilst I have managed to set up my personal email, I have having trouble with my business email in that I can receive emails, but am unable to send and the message says 'this email address has been rejected by server'

    I am an iPad novice and whilst I have managed to set up my hotmail account on the iPad - I ham having trouble with my business email (I can receive emails, but cannot send and it says' email rejected by server'

    That sounds like a settings issue to me. Check with your IT depatment to make sure you have it configured properly.

  • Hey guys, I'm having trouble matching the colour of the image back ground (white) with the pre-set colour selection. is there a tool that can help me? thanks

    hey guys, I'm having trouble matching the colour of the image back ground (white) with the pre-set colour selection. is there a tool that can help me? thanks

    Your description of the problem is not quite clear so I made certain assumptions. I hope I am rigtht. I believe you have a color patch such as this:
    that you would like to place in an image area that has modeling in its white background. You do not want to lay in a flat color but rather to add a color and not lose the modeling or other background tone. The problem is, after making the selection, if you use Edit > Fill and set the Blending mode to Color, the white background remains white. The only colored background area may be an object's shadow or some similar area that is not pure white. (Image 2) It is an unsatisfactory result.
    If that is an accurate description of the problem, consider this:
    Image 1: The original image
    Image 2: Edit > Fill with the Blending mode set to Color. White remains white
    Image 3: Mode changed to Lab Color. Edit > Fill with the Blending Mode set to Color. Then return to RGB.
    (I would not normally use this green as a replacement color but since it is a Tiffany clock, I chose a light version of Tiffany's trademark color.)

Maybe you are looking for