Possible Loss of Precision

/* * * * * * * * * * * method quadtratize * * * * * * * * * * * * * * * *
* Method to convert rectangle into a square with approximately the same
* area - the closest possible for a square with an integer side.
public int quadratize()
     double recArea = Math.sqrt (myWidth * myHeight);
     double lenSide = recArea / 4;
     return lenSide;
i need to square root the recArea and round to nearest int. This is what i have so far, but it won't compile because it has a possible loss of precision. any suggestions on how to fix it?

milanocookies wrote:
did this.Did what? Your code is the same
do i change everything to int?It depends on what you are trying to achieve. Is your method supposed to return an int or a double? If double then you need to change your method signature. If int then you need to do what I already said and cast your variable to an int before you return it. If you don'tknow what I mean by "cast" then perhaps you could read about it in your textbook.

Similar Messages

  • Possible loss of precision and santiy

    I'm having a bit of a problem dealing with bitwise operators and the compiler complaining of
    possible losses of precision (although I know there won't be). So I constructed some "do or die" code ;
    public class byteWise {
         public static void main(String[] args) {
              byte a=1;
              byte b=64;
              byte c= a & b;
    and javac produced this reply:
    D:\Java\byteWise.java:5: possible loss of precision
    found : int
    required: byte
              byte c= a & b;
    ^
    1 error
    What does it mean, "found int, expected byte" ? There's no int in the entire source code.
    Please help!

    Possible loss of precision only denotes that a specific mathematical operation you are performing provides a value that of a data type different than that you are storing it into. It is simply type checking that is performed by the compiler. If you want to bypass this, then you need to do an explitic cast of the data type to the type that you are assigning the value.
    Example:
    double bob = 5.5;
    int jack = 3;
    int sue = bob + jack; //Possible loss of precision.
    int sue = (int)(bob + jack) //This tells the compiler I know what I am doing.
    -Jason Thomas

  • Possible loss of precision? Really weird!

    Hello!
    Can someone help me!? I wrote a short list to experiment with scope for variables.
    The list is right below the error-message WHICH BUGS ME TO DEATH!
    I can NOT understand where the 'possible loss of precision' could be??
    Another strange thing, when I change line 9 to: x += y; ... I get no error!?
    ---------- Java compiler ----------
    Scope.java:9: possible loss of precision
    found : int
    required: short
                   x = x + y;
    ^
    1 error
    Normal Termination
    Output completed (0 sec consumed).
    // The list...
    class Scope
         public static void main(String arguments[])
              short x = 10;
              System.out.println("x: " + x);
                   short y = 30;
                   x = x + y;
                   System.out.println(x);
              System.out.println(x);
    }

    And to make it more confusing, you don't get a loss of precision when you try to add two integers, not even when they sum up to a value bigger (or less) than an int (the result is just cut of to fit in an int, 32-bit).
    int x = Integer.MAX_VALUE+5;
    long y = Integer.MAX_VALUE+5;
    long z = Integer.MAX_VALUE+5L;
    System.out.println("x = "+x); // -2147483644
    System.out.println("y = "+y); // -2147483644
    System.out.println("z = "+z); // 2147483652Actually I thought that y would show the correct result, but it doesn't because adding to ints will still be an int. For z I add an int and a long, so the result is a long. :)

  • Possible loss of precision - sorting 3 arrays respectively

    I have the following 2 arrays which need to be sorted according to a high-to-low sorted float array called avg. So float avg[5] is sorted high-to-low, and then String names[] is sorted respectively, for instance, before the sort, names[3]="Marty" and avg[3]=75, and after the sort 75 was in avg[0] because it was the highest, now Marty needs to be in names[0]. The same is with the int scores[5][8] array, the 5 rows need to be sorted corresponding to the new sorted avg array. Anyways here are the arrays and the sorting code i have. I get the error "possible loss of precision." Also the code tag on the forums isnt working for some reason.
    Arrays:
    float avg[]=new float[5];
    int temp[] = {34, 24, 78, 65, 45, 100, 90, 97, 56, 89, 78, 98, 74, 90, 98, 24, 45, 76, 89, 54, 12, 20, 22, 55, 66};
    String names[] = {"Mary","John","William","Debbie","Ralph"};
    int scores[][]= new int[5][8];
    for(a=0;a<=4;a++)
    for(b=0;b<=4;b++,c++)
    scores[a] = temp[c];
    Sort:
    public float sort(int[][] scores,String[] names, float avg[])
    int g,r,c,d,e;
    String q;
    for (r=0;r<=3;r++)
    for (g=r+1;g<=4;g++)
    if (avg[r]<avg[g])
    c=avg[r];
    avg[r]=avg[g];
    avg[g]=c;
    q=names[r];
    names[r]=names[g];
    names[g]=q;
    for(d=0;d<8;d++)
    e=scores[r][d];
    scores[r][d]=scores[g][d];
    scores[g][d]=e;

    The first time I got that error I misread it and got very excited: "possible lots of precision."
    Any way, you should point out the line where this occurs:
    c=avg[r];Here, c is an int and avg[r] a float. When you assign a float to an int, you loose
    the factional data, and as well, float have hold larger values than int. Why not make c a float?

  • Possible loss of precision with pi

    I'm trying to calculate the area of an oval but when I compile I get the error 'possible loss of precision
    public class Shapes extends Applet implements ActionListener
         Button buttonOval, buttonRectangle;                                        //Declaration of button variables
         Font fontVerdana;                                                            //Declare fonts
         TextField textx, texty, textwidth, textheight, areatext;          //Declare text fields
         Label labelx, labely, labelh, labelw;                                   //Declare label fields
         private boolean rectangleYesNo = false;
         final double pi = 3.142;                                //This is the variable I want to use to help calculate the area
         int x;                                                                           //Declare variable x as an integer value
         int y;
         int height;
         int width;
         int arearect;
         int areaoval;
         int radius;Then the code which should execute when the button is pressed (to work out the area) is...
    public void actionPerformed(ActionEvent ev)
              if (ev.getSource() == buttonRectangle)
                   x = Integer.parseInt(textx.getText());
                   y = Integer.parseInt(texty.getText());
                   width = Integer.parseInt(textwidth.getText());
                   height = Integer.parseInt(textheight.getText());
                   rectangleYesNo = true;
                   repaint();
                   arearect = width * height;
                   areatext.setText("The area is = " + arearect + "cm�");
                   areatext.setEditable(false);
              else if (ev.getSource() == buttonOval)
                   x = Integer.parseInt(textx.getText());
                   y = Integer.parseInt(texty.getText());
                   width = Integer.parseInt(textwidth.getText());
                   height = Integer.parseInt(textheight.getText());
                   rectangleYesNo = false;
                   repaint();
                   radius = width/2;
                   areaoval = radius * radius * pi;                  //This is where the error occurs!
                   areatext.setText("The area is = " + areaoval + "cm�");
                   areatext.setEditable(false);
              }I've changed it to float pi = 3.14f; but that still generates this error. Any ideas of how I can get this to successfully compile?
    I appreciate any help.
    Thanks!

    BIJ001 wrote:
    What is the difference?
    int areaoval;
    double areaoval;
    And in case that's not clear - areaoval (sic, standards suggest areaOval instead) is int. You can get rid of the error message by casting the result - which is a double - to an int, but rather, just make the resulting value fit into another double by changing areaOval a double.
    Clarity posting unnecessary ;o)

  • Possible Loss Of Precision Error

    I am a student that is new to Java and I am trying to create a simple Palindrome method.
    I get a "Possible loss of precision" error at:
    first = first + 1;
    Do I have to include something like this:
    userText.charAt(+1)
    to allow it to compile correctly?
    The rest of my code may be a bit off but I am really stuck at this. Thanks for any help :)
    Here is my code:
    public class SimpleInput
    public boolean isPalindrome(String userText)
    int letters = userText.length();
    if (letters <= 1)
    return true;
    else
    char first = userText.charAt(0);
    char last = userText.charAt(letters-1);
    if (first == last)
    while (first == last)
    first = first + 1;
    last = last - 1;
    return true;
    else
    return false;
    Message was edited by:
    jaamki

    Thank you guys so much.
    My class compiles alright, but when I create a new SimpleInput() and use the isPalindrome method, it gives me "Error: cannot find symbol - variable madam". (madam is what I entered as userText).
    It should return true.. but I am completely stuck and it is probably because my code may not be completely finished.
    Explanation please?!
    (Here is my new code:)
    public class SimpleInput
    public boolean isPalindrome(String userText)
    int letters = userText.length();
    if (letters <= 1) {
    return true;
    } else { }
    char first = userText.charAt(0);
    char last = userText.charAt(letters-1);
    if (first == last)
    { while (first == last)      
    first =(char)(first ++);
    last = (char)(last --);
    return true;
    else
    return false;
    }

  • Error: possible loss of precision

    It seems very easy problem. But I can not understand why this is a problem? My code is:
    int items[];
    long current_capacity=250;
    items = new int[current_capacity];I want to get memory from heap that long length and type will be int. Is this illogical? Also, why this is an error? Why not warning?
    Regards.

    public static int consolidate ( Account acct1,Account acct2)
    if (acct1.acctNum == acct2.acctNum)
    System.out.println(" Same account cannot be consolidated\n\t Try again");
    else if (acct1.name.equals(acct2.name))
    return (acct1.balance + acct2.balance) ;
    Th above code in a class gave me a error:Error: possible loss of precision
    Can you help m correct th code-I would appreciate that very much.

  • Why "possible loss of precision"?

    I have a symbolic costant:
    private final byte[] COMANDI = {(byte)0xaa, 0x15, ...};
    then I have:
    byte cmd = Arrays.binarySearch(COMANDI, estraiByte(comando, 1));
    Why loss of precision and here under not?? Both COMANDI and cmd are byte ...
    byte cmd = (byte)Arrays.binarySearch(COMANDI, estraiByte(comando, 1));

    Arrays.binarySearch returns an index into the array. If you want the
    actual byte contents you would have to sayint ndx = Arrays.binarySearch(COMANDI, estraiByte(comando, 1));
    if(ndx < 0) {} // value not found!
    byte cmd = COMANDI[ndx];Obviously the index won't be good if the desired byte value isn't in the
    array.

  • Re: possible loss of precision

    Your problem is, that you are using a double where and int should be, I'm pretty sure. Find the line numbers where it says lost precition, then I can help.

    These are all good ideas on the subject but it is
    because of 64-bit binary...Erm, no. This is a complicated solution that doesn't address the problem. The problem is here:
    pricetotal = Double.parseDouble( Change );
    sum = Change - pricetotal;This code was later modified to this by another poster:
    sum = 0.5 + Double.parseDouble(Change) - pricetotal;To explain, the code is subtracting the value of pricetotal from itself, resulting in zero. This is then subtracted from 0.5, resulting in an answer of 0.5.
    It's simple subtraction, not any floating-point issue.

  • How do i make the compiler ignore loss of precision

    Hi i have the following code:
        public void Q1()
            float p = 665857.0;
            double dp = 665857.0;
            float q = 470832.0;
            double dq = 470832.0;
            p = p * p;
            q = q * q;
            dp = dp *dp;
            dq = dq * dq;
           float ans =  p - 2 * q;
           double ansd = dp - 2 *  dq;
           System.out.println (ans);
           System.out.println (ansd);
        }I get a error saying:
    cw2.java:11: possible loss of precision
    found : double
    required: float
    float p = 665857.0;
    ^
    cw2.java:14: possible loss of precision
    found : double
    required: float
    float q = 470832.0;
    ^
    I know this is happenging and i want the compiler to ignore it and continue..does anyone know what type of throw i need

    try
    float p = (float) 665857.0;
    or
    float p = 665857.0f;IHMO, The best option is don't use float unless it is an assignment or you have a VERY good reason.

  • Loss of Precision error?

    I am supposed to put together a program that does interest for 10 years for each rate of interest and I have to do it for 5,6,7,8,9 & 10 percent. I need to use a inner and outer for loop but for some reason I can't get it to work. I also had to add a scrolling pane to it. Here is my program and the errors it gets.
    import java.text.NumberFormat;
    import java.util.Locale;
    import javax.swing.*;
    public class Interest {
    public static void main( String args[] )
    double amount; // amount on deposit at end of each year
    double principal = 1000.0; // initial amount before interest
    // create NumberFormat for currency in US dollar format
    NumberFormat moneyFormat =
    NumberFormat.getCurrencyInstance( Locale.US );
    // create JTextArea to display output
    JTextArea outputTextArea = new JTextArea(20, 20);
    //attach a scroll pane
    JScrollPane scroller=new JScrollPane(outputTextArea);
    // set first line of text in outputTextArea
    outputTextArea.setText( "Year\tAmount on deposit\n" );
    // calculate amount on deposit for each of ten years
    for ( int year = 1; year <= 10; year++ ) {
    for( int rate=0.05; rate<=0.10; rate++ ){                   
    // calculate new amount for specified year
    amount = principal * Math.pow( 1.0 + rate, year );
    // append one line of text to outputTextArea
    outputTextArea.append( year + "\t" +
    moneyFormat.format( amount ) + "\n" );
    } // end inner for
    } // end outer for
    // display results
    JOptionPane.showMessageDialog( null, scroller,
    "Compound Interest", JOptionPane.INFORMATION_MESSAGE );
    System.exit( 0 ); // terminate the application
    } // end main
    } // end class Interest
    The error is
    Interest.java:31: possible loss of precision
    found : double
    required: int
    for( int rate=0.05; rate<=0.10; rate++ ){
    ^
    1 error
    Any help would greatly appreciated! Thanks!

    Interest.java:31: possible loss of precision
    found : double
    required: int
    for( int rate=0.05; rate<=0.10; rate++ ){
    ^
    1 error
    Any help would greatly appreciated! Thanks!In line 31 of your source code, you are assigning a double literal into an int variable. Since ints are whole numbers only, you will lose precision. In other words, setting int rate to 0.05 will actually set rate to 0. After the first execution of the loop, rate++ will set rate to 1, and the loop will exit.
    You need to make rate a double, and increment by the increment value ...
    for( double rate=0.05; rate<=0.10; rate += <someDoubleAmount> ){World spins
    RD-R
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Loss of precision

    Hi
    I have two variables:
    byte chksum;
    byte extr;
    I need to calculate a checksum by a simply xor:
    for ( ...) {
    chksum = chksum ^ extr;
    but the compiler says "possible loss of precision"; my checksum must have only one byte ...
    Do u have any suggestion?
    Thanks

    In 'byte' operations such as chksum ^ extr the arguments are first converted to integer so the result is an integer. You are then trying to convert back to a byte which the compiler, quite rightly, says may be a problem. Since you know that this is not a problem in your case you should use either
    chksum = (byte)(chksum ^ extr);
    or make chksum an int and conert to byte at the end of the computation.

  • Why loss of precision??

    Hi
    I have this part of code:
    int i;
    float j;
    switch (k) {
    case 1: j = 0.1; break;
    case 2: j = 0.01; break;
    Why in case statements compiler says "possible loss of precision?? I have defined double j and I solve the problem, but why??

    Java interprets floating point literals as double values. If you want floats, you'll need to cast the literal or specify it with the 'F' or 'f' suffix.
    Example:
    float j;
    j = 0.1F;

  • Loss of Precision from Model Class to Excel Worksheet

    I suspect I am not using the tableOptions syntax properly. Decimals out to 15 digits are being truncated. I note that in the excel manual custom format precision appears to be available out to 14 digits.
    Any clues appreciated , I also need to set column width to the amount necessary to show the digits. I admit 15 digits are a lot. This is interest rate data. Thanks for any assistance.
    //write the TableData to Excel
    function setExcelData(officeTable) {
    if (officeTable != null) {
    Office.context.document.setSelectedDataAsync(officeTable, { coercionType: Office.CoercionType.Table , tableOptions: {numberFormat: "##.###############"}} , function (asyncResult) {
    if (asyncResult.status == Office.AsyncResultStatus.Failed) {
    app.showNotification('Failure '+ asyncResult.error) ;
    else {
    app.showNotification('Success');
    Doyle

    Hi Doyle,
    >>Decimals out to 15 digits are being truncated
    15 digits is the maximum limit, you could refer the link below for moreinformation:
    #Excel specifications and limits
    https://support.office.com/en-us/article/Excel-specifications-and-limits-ca36e2dc-1f09-4620-b726-67c00b05040f?CorrelationId=eacd66b2-3329-4dea-bf98-ad815f2e837f&ui=en-US&rs=en-US&ad=US
    >> Loss of Precision from Model Class to Excel Worksheet
    What do you mean by “Loss of Precision”? Do you mean that you want to set the value with 15 digits, but it did not work when the digit of the value was less than 15, like when you format “15.123”, you got the value of “15.123” instead of “15.123000000000000”?
    If so, I am afraid that the value of the numberFormat was wrong. You need to set the numberFormat as “##.000000000000000”. The “0” digit placeholder displays insignificant zeros if a number has fewer digits than there are zeros in the format. However, Excel
    does not display extra zeros when the number that you type has fewer digits on either side of the decimal than there are # symbols in the format. The link below shows more details:
    # Create or delete a custom number format
    https://support.office.com/en-us/article/Create-or-delete-a-custom-number-format-83657ca7-9dbe-4ee5-9c89-d8bf836e028e?CTT=1&CorrelationId=1f342fe4-3c64-444a-96ce-2e62498bda51&ui=en-US&rs=en-US&ad=US
    >> I also need to set column width to the amount necessary to show the digits
    You could set the Cell width to show the digits, the link below shows more details about this.
    # How to: Format tables in apps for Excel
    https://msdn.microsoft.com/en-us/library/office/dn535872.aspx?f=255&MSPPError=-2147217396
    In addition, since the original issue is about the Loss of presicion, if you still have any issue about setting column width. I will recommend you post a new thread for the second issue.
    The reason why I suggested is:
    #1 There would be more community members to discuss the question.
    #2 For people who have the similar question, it would be easier for them to find the answer from a specific thread.
    Thanks for your understanding.
    Best Regards,
    Edward
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

  • Dollars and cents/loss of precision

    I'm going crazy here...
    I'm trying to calculate the rate of a product in cents per minute. In order to do that, I'm taking a dollar amount and dividing it by the number of minutes. So, this:
    dollarAmount = 19.80
    numMinutes = 120
    should give me
    dollarAmount/numMinutes = 16.5
    Instead, it is giving me 16.499998. AARGH!
    All the numbers I'm using are floats. Should these be doubles instead? Am I just completely insane? Has anybody run into this kind of loss of precision?
    Please help (and many thanks in advance).
    rebecca

    nevermind this question... i figured it out.
    for those of you who may have run into this, it seems that floating point values tend to run into problems with precision. by converting all my variables to doubles, i was able to get an accurate calculation.

Maybe you are looking for

  • IPhoto library from 7.1.5 to 5.0.4?

    I want to duplicate my iPhoto library onto a G5 mac running Tiger with iPhoto 5.0.4 it currently resides on an Intel Leopard machine with iPhoto 7.1.5 (which came with that Mac so i don't have the upgrade option right now) is this possible? when i ex

  • Can't get rid of on screen display while watching FIOS On-demand movie

    I'm watching a FIOS on demand movie for the first time. There's a box at the bottom of the picture with the move info, like how much time is left in the movie,  etc. How can I get this to disappear?  If I press exit on remote, it disappears only brie

  • Need help in deleting old searches

    How can I delete old Google searches from my I Pad?  Going to Settings, to Safari, clearing history,eyc. Does not work.

  • How do I reset video output from reboot?

    I entered a resolution that didn't work with my TV and now I can not see my mini display.  How can I reset my resolution settings from a reboot? Thanks,

  • Reader 9 error in Visual Studio App

    I am getting an error in Visual Studio when a pdf document opened in the IE WebBrowser.  The error is the common memory error: "Instruction at "0x00000x000" referenced memory... " The error only happens in with Windows XP (not Vista) with Reader 9.