Open Side Menu Go to the Top

06-08-2016 , 10:33 PM
My first semester Java professor, halfway through the course, told us to stop returning False because if anyone ever sees you do that irl and they find out he was our professor, he would be extremely embarrassed.
Programming homework and newbie help thread Quote
Programming homework and newbie help thread
$25m Guaranteed WPM on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Programming homework and newbie help thread
06-08-2016 , 10:54 PM
One more question, and then I really am done tonight. One of my assignments for the week is to modify a program that shows the compound interest over 5 10 years at 5% interest to include 10 years at 6, 7, 8, 9 and 10% interest. I have done this and my code looks like this:
Code:
package compoundinterest;

public class CompoundInterest {

    public static void main(String[] args) 
    {
        double amount;
        double principal = 1000.0;
        
        System.out.printf("%s%20s%n", "Year", "Amount on deposit");
        
        for (double rate = 0.05; rate <= 0.10; rate += .01)
        {   
            System.out.println("Year by year growth for a " + rate * 100 
                               + "% interest rate.");
            System.out.printf("%s%20s%n", "Year", "Amount on deposit");
            
            for (int year = 1; year <= 10; ++year)
            {
                amount = principal * Math.pow(1.0 + rate, year);
                System.out.printf("%4d%,20.2f%n", year, amount);
                
                if (year == 10)
                    System.out.println();
            }
        }
    }
}
My question is about the line I included to print "Year by year growth for an x% interest rate." When I run this program, it outputs 5.0%, 8.0%, 9.0%, and 10.0%, but 6 and 7 both get output as something like "6.000000001%". For the purpose of my assignment it doesn't even matter because I could just delete that line, but why is this happening? And why for only 6 and 7? WTF?

I guess I could also just output the rate as "0.06" instead of 6%, but I still just want to understand this.

Last edited by _dave_; 06-09-2016 at 02:12 AM. Reason: code tags
Programming homework and newbie help thread Quote
06-08-2016 , 11:07 PM
Not every number can be well represented as a floating point number. The result is you can input something like "6" and it'll get stored as the nearest thing that CAN be represnted, i.e. 6.0000000001%

This is about python but it's the same idea in most languages:
http://effbot.org/pyfaq/why-are-floa...inaccurate.htm
Programming homework and newbie help thread Quote
06-09-2016 , 02:13 AM
LBloom, put your code in [code][/code] tags
Programming homework and newbie help thread Quote
06-09-2016 , 06:44 AM
Quote:
Originally Posted by LBloom
One more question, and then I really am done tonight. One of my assignments for the week is to modify a program that shows the compound interest over 5 10 years at 5% interest to include 10 years at 6, 7, 8, 9 and 10% interest. I have done this and my code looks like this:
Code:
package compoundinterest;

public class CompoundInterest {

    public static void main(String[] args) 
    {
        double amount;
        double principal = 1000.0;
        
        System.out.printf("%s%20s%n", "Year", "Amount on deposit");
        
        for (double rate = 0.05; rate <= 0.10; rate += .01)
        {   
            System.out.println("Year by year growth for a " + rate * 100 
                               + "% interest rate.");
            System.out.printf("%s%20s%n", "Year", "Amount on deposit");
            
            for (int year = 1; year <= 10; ++year)
            {
                amount = principal * Math.pow(1.0 + rate, year);
                System.out.printf("%4d%,20.2f%n", year, amount);
                
                if (year == 10)
                    System.out.println();
            }
        }
    }
}
My question is about the line I included to print "Year by year growth for an x% interest rate." When I run this program, it outputs 5.0%, 8.0%, 9.0%, and 10.0%, but 6 and 7 both get output as something like "6.000000001%". For the purpose of my assignment it doesn't even matter because I could just delete that line, but why is this happening? And why for only 6 and 7? WTF?

I guess I could also just output the rate as "0.06" instead of 6%, but I still just want to understand this.
Generally speaking, you should generate values that match the precision of your calculations. In this case you are working with a precision of 10**-2. You should format your output accordingly. You should also round to the nearest 10**-2. For example, 6.0051 should rounded to 6.01 and 6.00001 should be rounded to 6.00. Working with fractional values in programming is a little messy but can be very interesting, at least to me.

Last edited by adios; 06-09-2016 at 06:51 AM.
Programming homework and newbie help thread Quote
06-09-2016 , 07:27 AM
I would avoid floating point numbers in control structures as much as possible.

Code:
for (int percentage = 5; percentage <= 10; percentage += 1)
{
  double rate = percentage / 100.0;
  // rest of code
}
Programming homework and newbie help thread Quote
06-09-2016 , 08:41 AM
Yeah, doubles/floats and comparisons can be tricky. Heaven forfend you ever try to check for equality instead of inequality.
Programming homework and newbie help thread Quote
06-09-2016 , 04:22 PM
A C++ question:

Speaking of doubles, floats, integers...

In a program I'm making for a homework assignment, there is a point where I have to add the value of two doubles say x and y (both of which have a fractional part of exactly .5) and store the value in a new variable, z. During future calculations in this program, I'm going to want to only get integer values. If I got a float value, I would have to eliminate the decimal part anyway. So my question is, is it appropriate to just save myself some trouble and just declare z as an int? Since the numbers are x.5 and y.5, they will always equal a whole number, and tests appear to show no problems, except a warning message I get from visual studio that some data may be lost.

Alternatively, I could wait until I produce the final double value and just cast it into an integer, which seems like maybe it is better for (in this case extremely hypothetical) reuse.

If it helps the program is to determine how many "moshers" of a given size can fit in a mosh pit of a given size with given sized barriers, so end result must be a whole number obviously.
Programming homework and newbie help thread Quote
06-09-2016 , 05:41 PM
The warning is only shown if you do not explicitly tell it you want a float to be an integer (and accept potential loss of precision).

So instead of just assigning the value of two floats added together, you can cast the result to integer. That makes it obviously clear what you are doing. Both for the compiler and others looking at the code.

E.g.
Code:
double x = 1.5;
double y = 3.5;
int foo = (int)(x+y); // no warning, you seem to be aware of what's happening
int bar = x+y; // warning, precision lost
Programming homework and newbie help thread Quote
06-09-2016 , 08:03 PM
Quote:
Originally Posted by LBloom
A C++ question:

Speaking of doubles, floats, integers...

In a program I'm making for a homework assignment, there is a point where I have to add the value of two doubles say x and y (both of which have a fractional part of exactly .5) and store the value in a new variable, z. During future calculations in this program, I'm going to want to only get integer values. If I got a float value, I would have to eliminate the decimal part anyway. So my question is, is it appropriate to just save myself some trouble and just declare z as an int? Since the numbers are x.5 and y.5, they will always equal a whole number, and tests appear to show no problems, except a warning message I get from visual studio that some data may be lost.

Alternatively, I could wait until I produce the final double value and just cast it into an integer, which seems like maybe it is better for (in this case extremely hypothetical) reuse.

If it helps the program is to determine how many "moshers" of a given size can fit in a mosh pit of a given size with given sized barriers, so end result must be a whole number obviously.
Quote:
Originally Posted by kazana
The warning is only shown if you do not explicitly tell it you want a float to be an integer (and accept potential loss of precision).

So instead of just assigning the value of two floats added together, you can cast the result to integer. That makes it obviously clear what you are doing. Both for the compiler and others looking at the code.

E.g.
Code:
double x = 1.5;
double y = 3.5;
//int foo = (int)(x+y);
int foo = static_cast<int>(x+y); // no warning, you seem to be aware of what's happening
int bar = x+y; // warning, precision lost
A little more descriptive, results the same
Programming homework and newbie help thread Quote
06-10-2016 , 03:17 AM
In other C-style languages, for instance C#, not explicitly casting to int would be a compile error. Generally better to be explicit about what you're doing.
Programming homework and newbie help thread Quote
06-10-2016 , 07:00 AM
java/android question: doing some basic intro app progamming wile insomnic. The code as follows:

Code:
mPrevButton = (Button) findViewById(R.id.prev_button);
        mPrevButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
                updateQuestion();
            }
        });
    }

    private void updateQuestion() {
        int question = mQuestionBank[mCurrentIndex].getTextResId();
        mQuestionTextView.setText(question);
    }
gives me:

Quote:
java.lang.ArrayIndexOutOfBoundsException: length=5; index=-1
when I try to wrap around from the first question to the last one, backwards. (i.e. go from array index 0 to length - 1)

now, google assures me that (0-1) % 5 == 4, so a 5 length array should not be out of bounds if it's trying to access index 4. But it seems to be trying to access index -1 if I'm reading that error right.

What's going on here? I would try to debug but i've no clue how to do that in androind studio/intelliJ or whoever makes it, and also i'm very sleepy/foggy headed

edit:

ugh

found a similar issue in javascript, apparently the solution is:

Code:
mCurrentIndex = (((mCurrentIndex - 1) % mQuestionBank.length) + mQuestionBank.length) % mQuestionBank.length;
which is really beautiful and elegant

Last edited by Loki; 06-10-2016 at 07:16 AM.
Programming homework and newbie help thread Quote
06-10-2016 , 07:12 AM
Doesn't % give you the remainder in Java, which would be -1, as also seen in the error message?

http://stackoverflow.com/questions/5...gative-numbers
Programming homework and newbie help thread Quote
06-10-2016 , 07:16 AM
Modulus of negative numbers in programming is just a matter of convention. In Java a negative number mod a positive number is negative and -1 % 5 is -1.
Programming homework and newbie help thread Quote
06-10-2016 , 07:20 AM
The Wikipedia article on modulo has a table of how modulo is calculated in various languages. There are plusses and minuses, no pun intended, to different approaches.
Programming homework and newbie help thread Quote
06-10-2016 , 07:23 AM
>.<

i must not be using java 8 because i don't have Math.floorMod(). :sad:
Programming homework and newbie help thread Quote
06-10-2016 , 09:11 AM
Code:
int x = y % z;
if(x < 0) x = y - x;
Programming homework and newbie help thread Quote
06-15-2016 , 12:14 PM
This is what I'm supposed to build:

Code:
puts "Text to search through: "
text = gets.chomp
puts "Word to redact: "
redact = gets.chomp

words = text.split(" ")

words.each do |word|
  if word != redact
    print word + " "
  else
    print "REDACTED "
  end
end
This is what I'm trying to do (I really want to understand how it works, so I'm trying different ways of achieving the goal):

Code:
puts "Say something!"
text = gets.chomp

puts "Wanna take it back?"
redact = gets.chomp

words = text.split (" ")

words.each do |everyword|
    if everyword = redact
    print "REDACTED "
  else
    print everyword + " "
  end
end
With my code it just prints REDACTED REDACTED REDACTED (REDACTED for every word). Even if "redact" variable is completely different from the "text". Why?

Besides that, do you think it's a good approach I'm taking, messing around like this? It's like my 4th hour into Ruby and, damn, it's fun, but in cases like this I feel silly.

Last edited by RV-; 06-15-2016 at 12:25 PM.
Programming homework and newbie help thread Quote
06-15-2016 , 12:25 PM
Is your second snippet a copy and paste version of the code you're running?

It looks like "if everyword = redact" might be an assignment statement, whereas "if everyword == redact" would compare the values. An assignment statement must return a truthy value, so that's why it's printing REDACTED for every word.

Also, Ruby tip: I think .split defaults to .split(" ") if you don't give it the (" ") parameter. I could be wrong, but worth a shot.
Programming homework and newbie help thread Quote
06-15-2016 , 12:32 PM
Quote:
Originally Posted by Noodle Wazlib
Is your second snippet a copy and paste version of the code you're running?

It looks like "if everyword = redact" might be an assignment statement, whereas "if everyword == redact" would compare the values. An assignment statement must return a truthy value, so that's why it's printing REDACTED for every word.

Also, Ruby tip: I think .split defaults to .split(" ") if you don't give it the (" ") parameter. I could be wrong, but worth a shot.
Second is what I'm running. Had a space after .split - mistake. And YES! YES! YES! YES! It's that "double =" thing. And I should have known that by now, it was in the first couple of lessons. Shame on me.

Well at least my initial logic was ok... Thanks again! On to the next lesson!
Programming homework and newbie help thread Quote
06-15-2016 , 12:44 PM
Good luck! I know some of codecademy has issues, so if you work on something and can't figure it out, definitely check out their Q&A forum. Some people have figured out specific ways of loading the problems or answering in non-obvious ways to move on, even when your code should work.

But mostly, it's going to be stuff like typos or logic errors that get you. Happens to the best of us.
Programming homework and newbie help thread Quote
06-15-2016 , 09:40 PM
Quote:
Originally Posted by RV-
Second is what I'm running. Had a space after .split - mistake. And YES! YES! YES! YES! It's that "double =" thing. And I should have known that by now, it was in the first couple of lessons. Shame on me.

Well at least my initial logic was ok... Thanks again! On to the next lesson!
if you want to have even more fun with ruby, write ruby instead of C

Code:
words = text.split.map {|w| w == redact ? 'REDACTED' : w }
print words
also separate data and presentation
Programming homework and newbie help thread Quote
06-15-2016 , 10:36 PM
Let him get to method chaining before throwing all that at him, gawd!
Programming homework and newbie help thread Quote
06-15-2016 , 11:06 PM
Quote:
Originally Posted by Noodle Wazlib
Let him get to method chaining before throwing all that at him, gawd!
but the man needs something to look forward to...
Programming homework and newbie help thread Quote
06-16-2016 , 09:38 AM
Is there an easy way to explain why:

Code:
strings.each do |convert|
  symbols.push(convert.to_sym)
end
Works, but this one doesn't:

Code:
strings.each do |convert|
  convert.to_sym
  symbols.push(convert)
end
In second code it doesn't save new values(after .to_sym) and when we try to push we push restored version of |convert|? If so - why? If it's something else - what?

Last edited by RV-; 06-16-2016 at 09:45 AM.
Programming homework and newbie help thread Quote
Programming homework and newbie help thread
$25m Guaranteed WPM on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Programming homework and newbie help thread

      
m