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?

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

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

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

  • Sort an array of Application Class with respect to property

    class MyClass
    property string myProgram;
    property string myType;
    property string Description;
    end-class;
    Local array of MyClass &myProgArray;
    &myProgArray.Sort("D");
    I want to sort the Array in descending Order with respect to "myType".
    How to provide "myType" parameter to sort method ?
    Edited by: Mohsin on Oct 11, 2012 3:28 PM

    If you add myType to the array then you can sort on that, assuming you have different values for myType.
    According to PeopleBooks (8.51), API documentation;
    Sort(order)
    Note. This method works with arrays that have only one or two dimensions. You receive a runtime error if you try to use this method with an array that has more than two dimensions.

  • Sorting an array of filenames by filetype?

    I have an array of filenames read from a directory list. I
    can parse the
    file type from each filename using a function. How would I
    then sort the
    array by their respective file type, so that all PDF files
    sort together in
    the array, for example? Or would it be easier to just loop
    through the
    array by filetype, printing each matching array value?
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================

    That's exactly the code I am using except without the
    multisort. It should
    be an easy retrofit!
    Thanks, Joe!
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "Joe Makowiec" <[email protected]> wrote in
    message
    news:[email protected]...
    > On 14 Apr 2008 in macromedia.dreamweaver.appdev, Joe
    Makowiec wrote:
    >
    >> On 14 Apr 2008 in macromedia.dreamweaver.appdev,
    Murray *ACE* wrote:
    >>
    >>> I have an array of filenames read from a
    directory list. I can
    >>> parse the file type from each filename using a
    function. How would
    >>> I then sort the array by their respective file
    type, so that all
    >>> PDF files sort together in the array, for
    example? Or would it be
    >>> easier to just loop through the array by
    filetype, printing each
    >>> matching array value?
    >>
    >>
    http://www.php.net/manual/en/ref.array.php
    >>
    >> There are a bunch of sorting functions there.
    array_multisort and
    >> uasort both look interesting. Got code?
    >
    > Dropin for a directory listing in a <ul>:
    >
    > <pre>
    > <?php
    > $files2 = array();
    > if ($handle = opendir('.')) {
    > echo "Input: .\n";
    > echo "Directory handle: $handle\n";
    > /* This is the correct way to loop over the directory.
    > while (false !== ($file = readdir($handle))) {
    > $files[] = $file;
    > if (substr($file, 0, 1) != '.') {
    > $separator = split('\.', $file);
    > $files2[] = array('filename' => $separator[0], 'ext'
    =>
    > $separator[1]);
    > }
    > echo "$file\n";
    > }
    > closedir($handle);
    >
    > // print_r($files);
    > // print_r($files2);
    >
    > foreach ($files2 as $key => $row) {
    > $filename[$key] = $row['filename'];
    > $ext[$key] = $row['ext'];
    > }
    >
    > array_multisort($ext, SORT_ASC, $filename, SORT_DESC,
    $files2);
    >
    > // print_r($files2);
    >
    > reset($files2);
    >
    > }
    > ?>
    > </pre>
    > <ul>
    > <?php
    > foreach ($files2 as $myfile) {
    > echo "\t<li>";
    > echo $myfile['filename'];
    > echo (empty($myfile['ext'])) ? '' : '.' .
    $myfile['ext'];
    > echo "</li>\n";
    > }
    > ?>
    > </ul>
    >
    > Code's probably uglier than it needs to be, but it
    works.
    >
    > --
    > Joe Makowiec
    >
    http://makowiec.net/
    > Email:
    http://makowiec.net/contact.php

Maybe you are looking for

  • TS1538 Devices (iphone/ipod) show up on my computer but not on itunes!

    OKAY so i cannot connect any devise to itunes my iphone 5 and ipod are not being shown on itunes yet appear on my computer, i have uninstalled and re insalled itunes and gone through the proxy steps and all the steps on itunes help BUT IT WONT CONNEC

  • Itunes wont open just re-instail it opened first time and now it wont

    I had a problem with quicktime that forced me to unstail it and itunes and after the first time opening itunes after re-instailing it, it wont open. What am I supposed to do?

  • Lightroom 4 to Photo/Edit in Elements 10

    HELP, I just loaded Elements 10 on my new Big Mac, and when I select Photo/Edit In from LR4, Elements 10 opens, but will not open the image.  I've tried different settings, and have rebooted. 

  • IGoogle home page not loading correctly after update to 10.0.1. Help please!

    I use iGoogle as my home page. Since the update, the page displays minimal information, no gadgets or widgets, the theme heading or anything. Just the Google search box and some basic links. Howeer, if I click on Google Classic, that page displays co

  • Interactive slideshows

    Hi, I'm looking to make an interactive slideshow for my website. As a photographer, I would like to be able to have each categorical page of photos be easy to scroll through without clicking a large number of thumbnails. An example of what I would li