|
Thread Rules 1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution. 2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20) 3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible. 4. Use [code] tags to format code blocks. |
|
On October 13 2011 17:38 Morfildur wrote:Show nested quote +On October 13 2011 17:16 Blisse wrote:On October 13 2011 15:25 EvanED wrote: Very simply. Never use floating point numbers (doubles count) for money. :-)
(I'm not really kidding either. That really is something that basically no one should ever do.) What should I use for money then? The input has two decimal places... ? I don't remember getting these kinds of errors in Python, but I'm using C now, and the lesson is supposed to be learning how to deal with the doubles I think... Floating point numbers have problems with precision. On the first look they work, but then you end up having customers pay only 0.99 cent instead of 1 euro. For money you have to use a fixed point type (or in C you usually calculate with cents instead of euros/dollars) as they have exact instead of approximate representations.
Not possible. My input has two decimal places. That's why I'm having trouble. Would it help if I only ever rounded down? Currently I'm using floor(), but I think that's why I'm having problems...
EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case.
|
On October 14 2011 03:12 Blisse wrote: EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case. If you're using doubles, you've already lost.
Binary floating point numbers can't represent, say, 10 cents exactly. The proper way to store monetary values is in numbers of cents in an integer. (Or if you're interested in some fixed fraction of cents, the number of those fractions.) And if int isn't big enough for you (it will be on most systems and compilers nowadays, but isn't technically guaranteed), there is always long.
|
On October 14 2011 03:12 Blisse wrote: EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case. As EvanED said, you should never touch floats or doubles when dealing with money. After verifying that the input is a valid number (and depending on how robust you want to be, keep in mind that other places in the world use a comma instead of a period), you should strip punctuation from the number and parse it into an integer of cents.
|
On October 14 2011 14:26 Sentient wrote:Show nested quote +On October 14 2011 03:12 Blisse wrote: EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case. As EvanED said, you should never touch floats or doubles when dealing with money. After verifying that the input is a valid number (and depending on how robust you want to be, keep in mind that other places in the world use a comma instead of a period), you should strip punctuation from the number and parse it into an integer of cents.
The input is an array of doubles. How would you strip the decimal?
For example, I'm given { 999.99, 999.99, 0.00} as an array input and I need to split this three ways and output the dollars and the cents.
Would I just go through the double array and put the values in an int array while multiply all the values by 100?
EDIT: Dies on tests called floatingpointprecision3 and 5. No idea why.
|
First time posting here, hoping I can at least be of some use.
On October 14 2011 14:30 Blisse wrote:Show nested quote +On October 14 2011 14:26 Sentient wrote:On October 14 2011 03:12 Blisse wrote: EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case. As EvanED said, you should never touch floats or doubles when dealing with money. After verifying that the input is a valid number (and depending on how robust you want to be, keep in mind that other places in the world use a comma instead of a period), you should strip punctuation from the number and parse it into an integer of cents. The input is an array of doubles. How would you strip the decimal? For example, I'm given { 999.99, 999.99, 0.00} as an array input and I need to split this three ways and output the dollars and the cents. Would I just go through the double array and put the values in an int array while multiply all the values by 100? EDIT: Dies on tests called floatingpointprecision3 and 5. No idea why.
Depends on what those tests are doing? Where do they come from?
You don't have to put them in a separate array if you're just looking for a grand total of dollars and a grand total of cents. Maybe I'm not understanding the exercise or what splitting it three ways entails.
I'm assuming this is opening coursework and that input validation/sanitation aren't critical? That is, it would seem that way, as the values are guaranteed to only have two decimal places. If not, then of course take steps to make sure the person feeding you the numbers isn't trying to break your program by messing with commas/decimal places/delimiters.
...But if I'm on the right track at all, you should be able to convert each double in the input array to an integer, then do some modulus and integer division to parse out the cents and dollar amounts respectively from that integer, and add them to a running total for each.
That at least seems like the overall approach if I understand it correctly. Maybe someone can verify/lambaste me for giving bad advice just to clarify.
|
Hey guys! I have a Python question. What is the nicest/shortest/wittiest code to create something iterable (order is not important) of tuples of integer coordinates with the format of ([0 - MaxX-1], [0 - MaxY-1])? I tried some generators, but all have some issues, and now im working with a one liner, but not sure its the best.
What i tired:
>>> [((x, y) for x in range(n)) for y in range(n)] [<generator object <genexpr> at 0x7f1318670f50>, <generator object <genexpr> at 0x7f13168c4050>] >>> ([(x, y) for x in range(n)] for y in range(n)) <generator object <genexpr> at 0x7f13168c40a0> >>> [[(x, y) for x in range(n)] for y in range(n)] [[(0, 0), (1, 0)], [(0, 1), (1, 1)]]
And i went with the third one, connected with the itertools library.
itertools.chain.from_iterable([[(x, y) for x in range(sizex)] for y in range(sizey)])
But there must be some nicer, more effective way, i know it.
|
On October 14 2011 16:08 AzurewinD wrote:First time posting here, hoping I can at least be of some use. Show nested quote +On October 14 2011 14:30 Blisse wrote:On October 14 2011 14:26 Sentient wrote:On October 14 2011 03:12 Blisse wrote: EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case. As EvanED said, you should never touch floats or doubles when dealing with money. After verifying that the input is a valid number (and depending on how robust you want to be, keep in mind that other places in the world use a comma instead of a period), you should strip punctuation from the number and parse it into an integer of cents. The input is an array of doubles. How would you strip the decimal? For example, I'm given { 999.99, 999.99, 0.00} as an array input and I need to split this three ways and output the dollars and the cents. Would I just go through the double array and put the values in an int array while multiply all the values by 100? EDIT: Dies on tests called floatingpointprecision3 and 5. No idea why. Depends on what those tests are doing? Where do they come from? You don't have to put them in a separate array if you're just looking for a grand total of dollars and a grand total of cents. Maybe I'm not understanding the exercise or what splitting it three ways entails. I'm assuming this is opening coursework and that input validation/sanitation aren't critical? That is, it would seem that way, as the values are guaranteed to only have two decimal places. If not, then of course take steps to make sure the person feeding you the numbers isn't trying to break your program by messing with commas/decimal places/delimiters. ...But if I'm on the right track at all, you should be able to convert each double in the input array to an integer, then do some modulus and integer division to parse out the cents and dollar amounts respectively from that integer, and add them to a running total for each. That at least seems like the overall approach if I understand it correctly. Maybe someone can verify/lambaste me for giving bad advice just to clarify.
Thanks. This is an assignment for school.
I don't put the inputs in an array. They're given to me in an array. Or more specifically, I submit my code electronically and they run it through test cases that I don't know, and tell me whether I passed them all or not. The test cases they run are supposed to try and break my function, not my code. I don't need to check for negatives or 0.000 numbers, or whether the total is greater than 1 million, those are the constraints on their end.
I did what was suggested and converted stuff to int, but it doesn't pass. Precision and sumerrors.
Anyways, I got it to pass by using doubles, multiplying by a 1,000,000 and then doing calculations, undoing the multiplication and converting to int at the end for output. I don't think I needed the second array as that was from when I was still using int, but I don't feel like changing it since it works fine. 
Ints couldn't store enough digits for me to have a precision of 5 I think, which seems to mean a precision of 0.00001. I was going to choose like 1,000,000,000 instead of 1,000,000 if that didnt work... lol
+ Show Spoiler + void printAverageAmount(double money[], int n) { int i; double temp[n]; double sum = 0; for (i = 0; i < n; i++) { temp[i] = money[i]*1000000; } for (i = 0; i < n; i++) { sum += temp[i]; } double split = sum / n; /*printf("%d", split);*/ double dollars, cents;
dollars = split / 1000000; cents = (int)(split/10000) % 100; printf("Everyone gets %d dollar(s) and %d cent(s).\n", (int)dollars, (int)cents); }
|
if you are required to use a double[] as your input, you might want to ignore the most of this post. Just be informed that the multiplication by 1000000 in theory doesn't change anything. can you however chose to not use double in the first place, you should avoid it. Details below. but keep in mind, if you get your inputs as double[], there's no real point in converting them to int/float, because the precision is already lost and you can't regain it anyways.
------
multiplying a double by 1000000 doesn't really increase precision, it only makes the double store a "5 more zeroes at the end" since doubles are internally stored as 1.01010110 * 2^15, the decimal point is always moved such that there is only a 1 in front. so multiplying by 1000000 changes the bits a little bit (since there's a few 5 factors in there that can't be converted to 2^x), but in the end you end somewhere at 1.10010010*2^35 which has the same amount of bits to store the precision as before. So basically, if you use a float, and store a value of 5, it rounds at .00000001. But when storing a value of 5000000, it rounds at .01 already. So you actually don't gain any precision. (these are arbitrary values for demonstration purposes, to find the proper length of rounding you'd have to think in binary and use the correct bit lenghts for the fields, read up on IEEE floating point if you want details.)
also, you should not calculate money using floating point data types because they to weird rounding stuff and you might end up donating or disintegrating some value when handling large amounts (because, as i said, the decimal point is moved up to store as 1.xxx*2^y, so basically it can't store values consisting of more than 20 or so bits in "length" without rounding, and even values below that, like .02, must be expressed as some weird bit mask because it's basically stored as a sum of powers of 1/2, with which you just can't express .02 correctly because it has 5s in the factors).
so, have you tried using long? like float -> double for precision of floating point numbers, its int -> long for integer numbers. So basically, instead of capping at around 2 million (or 4 million for unsigned int), it caps at 8 million million (or 16 million million = 4 million squared for unsigned long). (values without guarantees, i *think* they are correct but i didn't look them up)
when calculating money, you should always calculate int or long, counting the cents. so $1.20 is actually "int money = 120; //cts", instead of doing the "human" thing and storing "float money = 1.2; //$".
|
On October 14 2011 16:53 MisterD wrote:when calculating money, you should always calculate int or long, counting the cents. so $1.20 is actually "int money = 120; //cts", instead of doing the "human" thing and storing "float money = 1.2; //$".
Or even better (and: safer): create a type for it 
Edit: okay, read back, its a C course. But still, C can emulate the C++'s functionality very well in these basic levels, its not really a type, only a bunch of data with some helper functions
|
Yeah, sadly, this assignment was I think a lesson in handling floating point.
The input is double array[n] = { 0.00, 0.00, 0.00 } for example.
You're saying about the multiplication by a million that my code would pass without it as well?
|
Hello! I'm pretty new to programming, as i just started studying java as a part of my game design bachelor this year.
Anyway, i'm supposed to turn normal english statements into logical tests that could be used in an if/else statement.
The english statement is "y is a multiple of z" i couldn't figure it out so i checked the correct answer, and it is: y % z == 0
Any idea why this is? Thanks
|
On October 14 2011 17:30 Wamic wrote:Hello! I'm pretty new to programming, as i just started studying java as a part of my game design bachelor this year. Anyway, i'm supposed to turn normal english statements into logical tests that could be used in an if/else statement. The english statement is "y is a multiple of z" i couldn't figure it out so i checked the correct answer, and it is: y % z == 0 Any idea why this is? Thanks 
The percentage sign is "modulo", which you'll be familiar from kiddie-maths as a "remainder" function.
The result is the remainder between z and the next highest number which is a factor of y. IE: The remainder
so 9%4 = 1 (4*2 = 8, 1 less than 9), 17%3 = 2 (3*5 = 15, 2 less than 17), etc, etc.
Good luck.
|
On October 14 2011 17:30 Wamic wrote:Hello! I'm pretty new to programming, as i just started studying java as a part of my game design bachelor this year. Anyway, i'm supposed to turn normal english statements into logical tests that could be used in an if/else statement. The english statement is "y is a multiple of z" i couldn't figure it out so i checked the correct answer, and it is: y % z == 0 Any idea why this is? Thanks 
% is the modulo operation.
y % z = x means that x is the rest of the division y / z.
So, "y is a multiple of z" is equivalent to "0 is the rest of the division of y by z", which is : y % z = 0
|
Thanks guys 
you may (or may not) enjoy this :p Lady Java
|
When you deal with serious business (particularly money) that must be infinitely precise in base-10, you use binary encoded decimals. Use 4 bits to represent every digit. You'll lose storage space (4 bits can represent up to 16 numbers, but you're only using them to store 10), but you gain precision. Use a byte for every 2 digits you need, and you're golden.
Of course, you'll end up having to use specialized operators to do arithmetic. This stuff is usually implemented in hardware because whoever needs it also wants speed (like banks). For homework, which will probably not have a problem with performance, I'd suggest using strings. You could implement basic arithmetic operators with loops that emulate what you'd do by hand (O(n^2) for division and multiplication).
If your input is in a double format, I'd assume that the input itself is represented well enough not to worry (2.34 will print as "2.34" on the screen). So, you could convert it to a string, and convert it to 100*(input) by parsing the characters to ints one at a time and multiplying by 10. When you're done, you print your output 1 character at a time, inserting a decimal point as appropriate.
|
On October 14 2011 17:10 Blisse wrote: Yeah, sadly, this assignment was I think a lesson in handling floating point.
The input is double array[n] = { 0.00, 0.00, 0.00 } for example.
You're saying about the multiplication by a million that my code would pass without it as well?
it should, yes.
|
On October 13 2011 02:14 Frigo wrote:+ Show Spoiler +On October 13 2011 01:58 Necosarius wrote: I have a hard time understanding recursion. Could someone please explain what it is/what it does? A recursive function might call itself with different parameters to compute its return value, that's all. For example, factorial calculation: public class Main {
public static void main (String[] args) { System.out.println(factorial(5)); }
public static int factorial (int n) { if( n == 0 ){ return 1; } return n * factorial(n - 1); }
} Another common example, calculating the Fibonacci number: public class Main {
public static void main (final String[] args) { System.out.println(fibonacci(7)); }
public static int fibonacci (int n) { if( n == 0 ){ return 0; } if( n == 1 ){ return 1; } return fibonacci(n - 1) + fibonacci(n - 2); }
}
On October 13 2011 05:49 Millitron wrote:+ Show Spoiler +On October 13 2011 01:58 Necosarius wrote: I have a hard time understanding recursion. Could someone please explain what it is/what it does? Recursion is a general idea for creating methods. A recursive method has a simple answer for some base case, and calls itself for any other cases. The recursive calls generally try to whittle the problem down to a base case, then merge the returns of each call. The Fibonacci and the factorial example, while being relatively easy to understand, are computationally very slow. There are much faster algorithms that don't use recursion.
On October 13 2011 07:00 killa_robot wrote:+ Show Spoiler +On October 13 2011 01:58 Necosarius wrote: I have a hard time understanding recursion. Could someone please explain what it is/what it does? Recursion just means a method calls itself until it reaches some sort predetermined value. In this case, the method calls itself until it reaches zero. Since it calls itself there's only ever one of it, so it's static.
public class Main { public static void main (final String[] args) { GetToZero(7); }
public static void GetToZero (int n) { if(n == 0) { System.out.println("Reached Zero"); } else if (n > 0) { System.out.println("Subtracting 1 - " + n); n--; GetToZero(n); } else if (n < 0) { System.out.println("Adding 1 - " + n); n++; GetToZero(n); } } }
On October 13 2011 07:28 Kambing wrote:+ Show Spoiler +On October 13 2011 01:58 Necosarius wrote: I have a hard time understanding recursion. Could someone please explain what it is/what it does? First thing to recognize: programming is problem solving by decomposition. Given a problem, you decompose that problem repeatedly into smaller problems until the subproblems are manageable to solve on their own. For example, the problem of cooking spaghetti involves several subtasks such as buying the ingredients, preparing the sauce, preparing the meat, and the mixing it all together. In code, you typically use functions/methods to realize this decomposition, e.g., void cookSpaghetti() { buyIngredients(); prepareSauce(); prepareMeat(); mixIngredients(); }
With that in mind, recursion is a problem solving technique in which you recognize that the subproblems that you create are actually smaller versions of the original problem that you are trying to solve. To make this more concrete, imagine a line of folk waiting for the release of heart of swarm: front <(^^)> <(^^)> <(^^)> back
Now imagine that the person in the back of line is trying to figure out what place they are in line. One thing they can do is step out of line and count the number of people in front of them directly. However, instead of risking losing their place in line, they can ask the person in front of them: front <(^^)> <(^^)> <(^^)> back |-- "What place are you in line?"
Now, the person in front of them is posed with a similar question, so they can ask the person in front of them the same question: front <(^^)> <(^^)> <(^^)> back | |-- "What place are you in line?" |-- "What place are you in line?"
Finally the question is posed to the person in the front of the line. He's know he's #1, so he tells the person behind him. front <(^^)> <(^^)> <(^^)> back | | |-- "What place are you in line?" 1 |-- "What place are you in line?"
With that answer, the person behind the first in line now knows what place they are in line. They know they're second by adding one to the place of the person in front of them. front <(^^)> <(^^)> <(^^)> back | | |-- "What place are you in line?" 1 2
And finally the person in the back knows their place in line given the position of the person in front of them by adding one. front <(^^)> <(^^)> <(^^)> back | | | 1 2 3
This is the essence of simple recursion: - A base case that handles the situation when the problem we're trying to solve is directly solvable.
- A recursive case that solves the current problem by solving an identical subproblem of a smaller size.
Let's extend this to a code example that people have mentioned already, factorial(n). int factorial(int n) { // Base case, i.e., front of the line: 0! = 1 if (n <= 0) { return 1; // Recursive case, i.e., the middle or the line: n! = n * (n-1)! } else { return n * factorial(n-1); } }
Wow thank all for the replies!
|
Managed to get Ant and JUnit working together. It was a bit tricky cause JUnit takes the package name from the relative path given by Ant, instead of y'know, the actual package declaration inside the java files. So instead of jfrigo.test.math.PolynomialTest, it tried to run test.math.PolynomialTest or even math.PolynomialTest, without any success of course.
The solution is trivial, but it took me a while to think outside the box and realize the trick. We simply run it from the parent directory and give a longer relative path 
<batchtest fork="yes" todir="report"> <formatter type="plain"/> <fileset dir=".."> <include name="jfrigo/test/**/*.java"/> </fileset> </batchtest>
Wrote a simple unit test as practice. Managed to catch a few silent errors in a seemingly perfect Polynomial implementation: wrong result at integration of the zero polynomial, sign error at definite integration, empty toString for the zero polynomial, and an invariant violation due to some one-off error.
Moral of the story: automated unit tests are fukken awesome.
|
On October 14 2011 17:30 Wamic wrote:Hello! I'm pretty new to programming, as i just started studying java as a part of my game design bachelor this year. Anyway, i'm supposed to turn normal english statements into logical tests that could be used in an if/else statement. The english statement is "y is a multiple of z" i couldn't figure it out so i checked the correct answer, and it is: y % z == 0 Any idea why this is? Thanks 
% returns the remainer of the statement after division.
so 2%2 = 0 3%2 = 1 4%2 = 0
etc
if its evenly divisible then x%y would = 0
|
|
|
|