Floating point rounding error

I've been working on an egyptian fraction program and for some reason I cant seem to figure out a way to fix this rounding error. An egyptian fraction is a fraction that can be expressed as a sum of fractions eg. 3/4 = 1/2 + 1/4. For some reason on certain fractions it rounds up and skips the correct fraction to subtract. When I run 2/7 its supposed to equal 1/4 + 1/28, but gives me 1/4 + 1/29 and decides to round. This is my code for the problem.
public class EgyptianFraction{
    private static double epsilon = 1.0e-7;
    public static void main(String args[]){
        greedySearch(2.0/7.0);
    public static void greedySearch(double fraction){
        for(int i = 2; fraction > epsilon; i++){
            if(fraction - (1.0/i) >= 0){
                fraction -= (1.0/i);
//*****Output******
//0.0357142857142857 - 0.03571428571428571 = -1.3877787807814457E-17
}When I print out all of the math involved it says that it gives the output above. They are fairly close but for some reason it makes the 1/28 bigger then the current fraction. The program should subtract 1/28 and then the fraction should be close enough to 0 and end. Is there any way you guys can think of to fix this problem?

You have given the error as epsilon, so you can't expect `fraction - 1.0/i >= 0` to give an exact answer.
Given your error is +/- epsilon, this expression should be
fraction - 1.0/i >= epsilon || fraction - 1.0/i >= -epsilon
or just
fraction - 1.0/i >= -epsilon
If you change this you get 1/4 + 1/28 as the answer,

Similar Messages

  • "Floating point exception" error

    hello :
       i install sap 4.7 in redhat, after using ./install that extracting the files to instdir ,
    the sapinst don't can start setup and present the error "floating point exceprion"
    please help me!
    thanks

    Dear dongyang xu,
    what is your patchlevel of rhel3? Please make sure, that you run the latest Quarterly Update of RHEL3 which is QU9 if I remember correctly.
    Please make also sure, that you are using the latest available sapinst for R/3 4.7 Enterprise.You can download it from <a href="http://service.sap.com/patches">http://service.sap.com/patches</a>.
    Additionally, what version of java have you installed? What's the output of:
    'java -version' and
    'echo $JAVA_HOME'
    Thanks
    Hannes Kuehnemund
    SAP LinuxLab

  • Dtrace Floating Point gives error on x86

    When I try to create a floating point constant in dtrace x86:
    BEGIN
    printf ("%f", 1.0);
    exit (1);
    I get the error:
    dtrace: failed to compile script special.d: line 3: floating-point constants are not permitted
    Am I using the floating point constant incorrectly, or are floating point constants not permitted in the x86 platform.
    Thanks,
    Chip

    Then what is meant at the bottom of page 48 of the
    Solaris Dynamic Tracing Guide where it talks about
    floating-point constants?
    ChipSorry for not making that sufficiently clear. We are reserving that syntax for possible future use, but you cannot specify floating-point constants at present, and you cannot perform floating-point arithmetic in D. The only legal use of floating-point is that you can trace one or more data objects or structures that contain floating-point values and format the results using printf() and the various %f, %g formats.
    -Mike

  • Float point round issue

    hi
      here is a problem: i have created cubes, transfer role, update role etc...
    and i transport these elements from develop server to production server.
    In develop server, when i upload data, the data float point would not be changed,
    not be rounded, but in production server, the float data has been rounded.
    and the transfer role, update role are the same between develop and production server, can someone helps me? hunger for your advice, thanks !!

    thanks,but that place is for Decimal Notation.i mean the data has been rounded in production server ,
    eg :
    before upload
    123.678
    after upload
    124
    so i think the decimal notation setting isn't the point.

  • Multiply floating point rounds

    Why is it that when I use the Multiply function with two floating point numbers, that it rounds off the result?
    I have the Format/Precision set to 3 decimals on the indicator.
    The inputs are both doubles.
    Using a probe before the indicator shows that the result is rounded by the mulitply function itself.
    Attachments:
    Multiply Rounding.vi ‏7 KB

    Wes_OH wrote:
    I have the Format/Precision set to 3 decimals on the indicator.
    NO!
    Your indicator is set to six digits of precision, thus shows only six significant digits and that's exactly what you get (324975). If you would set ot to 3 signiificant digits, it would display as (325000).
    If you want to show a certain number of digits after the decimal point, you need to set the "precision type" to "Digits of Precision", not "significant digits", as you have it set now. Try it!
    Also don't trust any probes or indicators, they never "round", i.e. never change the data. The displayed precision is just cosmetic and does NOT change the underlying data that is carried in the wire, which is always full precision. If you want a probe with 10 decimal digits, create a custom probe.
    If you want to round, you need to do it in code.
    Message Edited by altenbach on 02-05-2007 08:37 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    digits.png ‏25 KB

  • Floating Point Arithmatic Error

    Hi,
    I know actionscript represents numbers and double precision
    floating point values. I'm having a problem where double arithmatic
    in actionscript doesn't match the results of the same double
    arithmatic in C++ / C#.
    EXAMPLE:
    In C++ / C#:
    double x, y, x1, y1;
    x = 209.4;
    y = 148.8;
    x1 = 203.0;
    y1 = 145.0;
    double ddx = x - x1;
    double ddy = y - y1;
    RESULT
    ddx: 6.4000000000000057
    ddy: 3.8000000000000114
    In Flash ActionScipt 2:
    var x, y, x1, y1;
    x = 209.4;
    y = 148.8;
    x1 = 203.0;
    y1 = 145.0;
    var ddx = x - x1;
    var ddy = y - y1;
    RESULT
    ddx: 6.39999999999992
    ddy: 3.80000000000024
    After researching Flash / Actionscript "var" stores numerical
    values as doubles ( 8 bytes ) just like doubles are stored in C++ /
    C# ( 8 bytes ). Why would there be a difference between the results
    of ddx and ddy? Are there different implementations of double
    floating point math? If so, Is there a way I can mimic the Flash /
    Actionscript version in C++ / C#?
    Any help would be great!
    Thanks!

    Hmmm, so you're saying the actual binary representation is
    the same but they're just displayed differently?

  • "Invalidation floating point ooperation" error mas...

    Did anybody else face this kind of error massage? My properly working Skype started it a few weeks ago and reinstallation doesn't help. What the hell is it? And how could I repair this error?
    Thx

  • Funny modulus result? If this a rounding error?

    Hi,
    Strangely, I'm getting the following result in the ESTK Javascript console:
    492.1 % 13.3
    Result: 13.3
    Clearly the result should be 0 (since 492.1 is a multiple of 13.3).
    What's going on? Is this because of floating-point arithmetic? In any
    case, what can I do about it to get an accurate result?
    Thanks,
    Ariel

    Thanks Stephen for your input.
    I don't think it says anywhere that the % operator should only be used
    with integers? At any rate, it seems to work fine with decimals in most
    cases.
    Your mod function seems rather strange to me: try a = 9, b = 3:
    a/b = 3
    3-9 = -6
    -6 * 3 = -18
    which clearly isn't the right answer for 9 % 3 ?
    At any rate, I've meanwhile established that this is a floating-point
    arithmetic error. Because, once again in the ESTK console, the following
    shows that what looks like 13.3 isn't:
    492.1 % 13.3
    Result: 13.3
    but....
    (492.1%13.3)-13.3
    Result: -3.5527136788005e-15
    So it looks like I'll have to do something like this to the result:
    myMod = a % b;
    if (Math.abs(myMod - b) < 0.00001) myMod = 0;
    ... which is the sort of thing that often needs to be done with floating
    point arithmetic, if I'm not mistaken.
    Thanks,
    Ariel

  • Designing for floating point error

    Hello,
    I am stuck with floating point errors and I'm not sure what to do. Specifically, to determine if a point is inside of a triangle, or if it is on the exact edge of the triangle. I use three cross products with the edge as one vector and the other vector is from the edge start to the query point.
    The theory says that if the cross product is 0 then the point is directly on the line. If the cross product is <0, then the point is inside the triangle. If >0, then the point is outside the triangle.
    To account for the floating point error I was running into, I changed it from =0 to abs(cross_product)<1e-6.
    The trouble is, I run into cases where the algorithm is wrong and fails because there is a point which is classified as being on the edge of the triangle which isn't.
    I'm not really sure how to handle this.
    Thanks,
    Eric

    So, I changed epsilon from 1e-6 to 1e-10 and it seems to work better (I am using doubles btw). However, that doesn't really solve the problem, it just buries it deeper. I'm interested in how actual commercial applications (such as video games or robots) deal with this issue. Obviously you don't see them giving you an error every time a floating point error messes something up. I think the issue here is that I am using data gathered from physical sensors, meaning the inputs can be arbitrarily close to each other. I am worried though that if I round the inputs, that I will get different data points with the exact same x and y value, and I'm not sure how the geometry algorithms will handle that. Also, I am creating a global navigation mesh of triangles with this data. Floating point errors that are not accounted for correctly lead to triangles inside one another (as opposed to adjacent to each other), which damages the integrity of the entire mesh, as its hard to get your program to fix its own mistake.
    FYI:
    I am running java 1.6.0_20 in Eclipse Helios with Ubuntu 10.04x64
    Here is some code that didn't work using 1e-6 for delta. The test point new Point(-294.18294451166435,-25.496614108304477), is outside the triangle, but because of the delta choice it is seen as on the edge:
    class Point
         double x,y;
    class Edge
         Point start, end;
    class Triangle
         Edge[] edges;
         public Point[] getOrderedPoints() throws Exception{
              Point[] points = new Point[3];
              points[0]=edges[0].getStart();
              points[1]=edges[0].getEnd();
              if (edges[1].getStart().equals(points[0]) || edges[1].getStart().equals(points[1]))
                   points[2]=edges[1].getEnd();
              else if (edges[1].getEnd().equals(points[0]) || edges[1].getEnd().equals(points[1]))
                   points[2]=edges[1].getStart();
              else
                   throw new Exception("MalformedTriangleException\n"+this.print());
              orderNodes(points);
              return points;
            /** Orders node1 node2 and node3 in clockwise order, more specifically
          * node1 is swapped with node2 if doing so will order the nodes clockwise
          * with respect to the other nodes.
          * Does not modify node1, node2, or node3; Modifies only the nodes reference
          * Note: "order" of nodes 1, 2, and 3 is clockwise when the path from point
          * 1 to 2 to 3 back to 1 travels clockwise on the circumcircle of points 1,
          * 2, and 3.
         private void orderNodes(Point[] points){
              //the K component (z axis) of the cross product a x b
              double xProductK = crossProduct(points[0],points[0], points[1], points[2]);
              /*        (3)
               *          +
               *        ^
               *      B
               * (1)+             + (2)
               *       ------A-->
               * Graphical representation of vector A and B. 1, 2, and 3 are not in
               * clockwise order, and the x product of A and B is positive.
              if(xProductK > 0)
                   //the cross product is positive so B is oriented as such with
                   //respect to A and 1, 2, 3 are not clockwise in order.
                   //swapping any 2 points in a triangle changes its "clockwise order"
                   Point temp = points[0];
                   points[0] = points[1];
                   points[1] = temp;
    class TriangleTest
         private double delta = 1e-6;
         public static void main(String[] args)  {
                    Point a = new Point(-294.183483785282, -25.498196740397056);
              Point b = new Point(-294.18345625812026, -25.49859505161433);
              Point c = new Point(-303.88217906116796, -63.04183512930035);
              Edge aa = new Edge (a, b);
              Edge bb = new Edge (c, a);
              Edge cc = new Edge (b, c);
              Triangle aaa = new Triangle(aa, bb, cc);
              Point point = new Point(-294.18294451166435,-25.496614108304477);
              System.out.println(aaa.enclosesPointDetailed(point));
          * Check if a point is inside this triangle
          * @param point The test point
          * @return     1 if the point is inside the triangle, 0 if the point is on a triangle, -1 if the point is not is the triangle
          * @throws MalformedTriangleException
         public int enclosesPointDetailed(LocalPose point, boolean verbose) throws Exception
              Point[] points = getOrderedPoints();          
              int cp1 = crossProduct(points[0], points[0], points[1], point);
              int cp2 = crossProduct(points[1], points[1], points[2], point);
              int cp3 = crossProduct(points[2], points[2], points[0], point);
              if (cp1 < 0 && cp2 <0  && cp3 <0)
                   return 1;
              else if (cp1 <=0 && cp2 <=0  && cp3 <=0)
                   return 0;
              else
                   return -1;
             public static int crossProduct(Point start1, Point start2, Point end1, POint end2){
              double crossProduct = (end1.getX()-start1.getX())*(end2.getY()-start2.getY())-(end1.getY()-start1.getY())*(end2.getX()-start2.getX());
              if (crossProduct>floatingPointDelta){
                   return 1;
              else if (Math.abs(crossProduct)<floatingPointDelta){
                   return 0;
              else{
                   return -1;
    }

  • R6002 - floating point not loaded / C++ Runtime Error

    Good Evening,
    I have been having this problem with Adobe Bridge for a while and tonight sat down to try and solve it. Fresh version of Windows XP reinstalled all programs and this is still happening! Any Ideas?
    This error only occurs with Adobe Bridge, I can load Photoshop etc.. all fine.
    Error:
    "Runtime Error!
    Program: C:\ProgramFiles\Adobe\Adobe Bridge CS3\Bridge.exe
    R6002
    - floating point not loaded"
    Here is a print screen..
    http://images.unbrokenphotography.co.uk/BridgeError.jpg

    Is there are answer to this problem?  This error message is appearing on an entire lab full of computers.  We are running Web Premium CS4
    I have tried to reset the Bridge Preferences:
    Hold down the Ctrl key and click on Bridge icon to start.
    Should get a reset window with 3 options.
    Choose the first option
    I still get "Runtime Error!   Program: C:\Prgram Files\Adobe\Adobe Bridge CS4\Bridge.exe  R6002 -floating point support not loaded"

  • Invalid Floating Point Error

    I have one Captivate 3 project published as a Stand Alone
    project with Flash 8 selected. There are 36 slides, no audio, no
    eLearning, SWF size and quality are high.
    One person who runs this gets an "Invalid Floating Point"
    error when he tries to run it the first time. He is running Windows
    XP SP2, Firefox 3.0.4. and Flash Player 10.0.12.36. Other Captivate
    projects I've created run fine for him. This one sometimes runs
    after the first Error message.
    Any thoughts on the cause and fix?
    Thanks,
    Janet

    iMediaTouch probably doesn't support Floating Point formats - it certainly doesn't mention them in the advertising. Try saving your files as 24-bit PCMs, and they should import fine.

  • Floating Point Error

    Hi all!
    Does anybody understands the following Error Message or does anybody had it allready?
    I <u>tried</u> to write a little 3D-Engine just for fun, but the kvm doesn�t wantme to.
    Please help.
    ERROR: floating-point constants should not appear
    Error preverifying class J2mewtk.apps.DDD_Engine.src.DDD_Engine.Matrix_Operation
    com.sun.kvem.ktools.ExecutionException: Preverifier returned 1
    Build failed
    Thx in prev..

    Ok, after years it even came to me that the KVM doesn�t support floatingpoint numbers. :-)
    I found the MathFP package to be usefull for me, but can someone tell me where i have to put the package, so that i can import it? I am trying since hours ... ;-)

  • Error on floating point?

    One can expect that 1.2 * 3.0 equals 3.60
    But the following statement has the result: 3.5999999999999996
    - System.out.println(1.2 * 3.0);
    Why?
    How can I control or estimate the floating point error?
    Thanks in advance!

    It is not a Java problem or a Java error. It is inherent to floating-point arithmetic.
    1.2 can not be exactly represented in binary floating-point arithmetic. But 1.25 (that is 5 * (2 ^ -2)) can be.
    If your problem requires exact decimal arithmetic, use BigDecimal instead. (It is very slow compared to the conventional floating-point arithmetic).
    Please consult a textbook on numerical calculus for the techniques of dealing with floating-point error - it depends on the algorithm that you use for solving your problem.

  • ERROR: floating-point constants should not appear

    ERROR: floating-point constants should not appear
    Error preverifying class KGUI.KLabel
    com.sun.kvem.ktools.ExecutionException: Preverifier returned 1
    Build failed
    I get this error after adding this code to my application:
         private int C=0;
         private float D=0.0f;
         private int H=0;
         private float store=0.0f;
         private int pos=0;
         private int SH=0;
    ..................some code.....................
         H=1+ROWS*(f1.getHeight());
         if(H/kawalki.length>0){
              C=H/kawalki.length;
              D=kawalki.length/(H%kawalki.length);
              SH=C;
              if(D>=0.5f)
                   SH++;
         }else{
              SH=1;
              D=kawalki.length/(H%kawalki.length);
    .................some code..............
    protected void keyPressed(int keyCode){
    int game=getGameAction(keyCode);
    switch(game){
    case UP:
    if (line>0){
    line--;
                   pos-=C;
                   store-=D;
                   if(store<0.0f){
                        pos--;
                        store=1.0f+store;
    repaint();
    break;
    case DOWN:
    if(line+ROWS<kawalki.length){
                   line++;
                   pos+=C;
                   store+=D;
                   if(store>=1.0f){
                        pos++;
                        store--;
    repaint();
    break;
    Can anybody help me quick?

    If the platform is CLDC 1.1 you can have floats. Run preverify to see the options. The cldc1.1 preverifier seems to have options to allow rejecting floats/doubles but the default seems to be to allow them.
    Usage: preverify [options] classnames|dirnames ...
    where options include:
    -classpath <directories separated by ';'>
    Directories in which to look for classes
    -d <directory> Directory in which output is written (default is ./output/)
    -cldc1.0 Checks for existence of language features prohibited
    by CLDC 1.0 (native methods, floating point and finalizers)
    -nofinalize No finalizers allowed
    -nonative No native methods allowed
    -nofp No floating point operations allowed
    @<filename> Read command line arguments from a text file
    Command line arguments must all be on a single line
    Directory names must be enclosed in double quotes (")

  • Who know this bug "ERROR: floating-point constants should not appear"

    anyone know how to solve this bug
    ERROR: floating-point constants should not appear
    Error preverifying class org.javabluetooth.stack.BluetoothStack
    com.sun.kvem.ktools.ExecutionException: Preverifier returned 1

    HI,
    it seems that ur using the package "org.javabluetooth.stack.BluetoothStack" in WTK1.0 or 2.0 which does not support floating point. The above package uses float data type. You can download the new version of WTK (2.1) which supports floating points.

Maybe you are looking for

  • Mac Mail at fault, says Bell.  True?

    Hello, I've used Macs since 1987, but (ironically) it's only with my new MacBook Pro (running Mavericks of course) that I'm constantly having to re-enter my password when trying to get or send mail from my Mail program.  (I think I used to have to do

  • Ultrabeat Problems

    I just recently found the ultrabeat setting with Logic Express and am having some trouble with it. Once I make my beat and am ready to put in into my song, when I drag the pattern box into the track, it plays through the whole song and not just the p

  • Cannot create PAL DV projects in iMovie HD6

    I'm wondering if anyone else is having this issue - or if I've missed something obvious! After having worked with iMovie for several years, always with DV-PAL camcorders, I suddenly find that when I create a new project it defaults to DV-NTSC. In the

  • Ichat video and audio not working

    They used to work just fine. Have no idea what is going on. I get the error 8 that every one around here is talking about. I've tried the suggestions of bandwidth, firewall etc. Don't know what else to do.

  • Selecting objects on the clipboard

    Hi, I have a program that draws circles on a JPanel. Now I'm trying to cut/ copy/paste these objects. I know I first need to select and object (a circle in my case) That is, get the system clipboard and then select an area/object My question is, how