Before I get into detail, YES this is a HOMEWORK ASSIGNMENT. NO I DON'T WANT ANSWERS, JUST TIPS and/or Suggestions to try this or that.
The problem introduces with this:
Create a class, ExactNumber, that uses two long properties named left
and right (representing the portion of the number that is to the left
and right of the decimal point respectively). For example, 3.75 would
be represented by new ExactNumber(3, 7500000000000000L). Note the L on
the end which tells Java the large number is a long. This translates
to: 3 + 7500000000000000/10000000000000000 = 3.75
Here is my code:
public class ExactNumber {
private long left;
private long right;
public ExactNumber(long left, long right) {
this.left = left;
this.right = right;
}
public String toString() {
return String.valueOf(doubleValue());
}
public double doubleValue() {
return ((double) left + (double) (right/ 100000000000000L) / 100);
}
public int compareTo (ExactNumber exactNumber) {
if(exactNumber.left < left) {
return 1;
}
else if (exactNumber.left == left) {
if (exactNumber.right < right) {
return 1;
}
else if (exactNumber.right == right) {
return 0;
}
else {
return -1;
}
}
else {
return -1;
}
}
public boolean equal(ExactNumber thisobject) {
if (thisobject instanceof ExactNumber) {
if (thisobject.doubleValue() == this.doubleValue()) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
public double add(ExactNumber exactNumber) {;
return ((left+exactNumber.left) + (double)((right+exactNumber.right)*1E-16));
}
}
My problem are the tests coming up as an error when the expected value is equal to the actual value. Here are the test cases (NOTE: there are more test cases, but they pass the JUnit test):
public class TestExactNumber extends TestCase {
ExactNumber threesevenfive = new ExactNumber(3, 7500000000000000L);
ExactNumber threesevenfive_andalittlebit = new ExactNumber(3, 7500000000000001L);
ExactNumber threesevenfive_dupe = new ExactNumber(3, 7500000000000000L);
ExactNumber ten = new ExactNumber(10, 0);
ExactNumber thirteensevenfive = new ExactNumber(13, 7500000000000000L);
ExactNumber sevenfifty = new ExactNumber(7, 5000000000000000L);
public void test_equals() {
assertFalse(threesevenfive.equals(threesevenfive_andalittlebit));
assertEquals(threesevenfive, threesevenfive_dupe);
}
public void test_add() {
assertEquals(threesevenfive.add(ten), thirteensevenfive);
assertEquals(threesevenfive.add(threesevenfive), sevenfifty);
The assertEquals above failed in the JUnit test, but says like (for an example) expected = 13.75 and actual = 13.75.
Any tips or hints at what I need to do with my code is greatly appreciated. And thank you in advanced.
NOTES:
According to my instructor, I should not be using the doubleValue method to implement my equals method. I know that I do have it in my code, but that was prior to the tip the instructor gave me and I am just unsure about how to change it.
I am using eclipse for java to code this.
Your equal Method is never used. The Java Method used by assertEquals() is called equalS (and you have to override the equals() method derived from Object).
Therefore, the assertion will use equals inherited from Object, which will compare the actual instances rather than using YOUR equal method which will compare the objet values. And since they are two different INSTANCES, they are not equal.
Finally, the two instances will be plotted with toString() resulting in expected = 13.75 and actual = 13.75. (Because your toString() returns only the values, ignoring the difference between instances)
Your Instructors Response:
A Long in Java is a 64 bit long number. Double in Java is implemented with the IEEE754 Standard, which only leaves 52 bit for the mantissa. Meaning: Any conversion of a Long Number to a double, where the Long Number has set bits on bit 53 to 63 - will cause the exponent to be shifted in a way, that you loose precision arround the LSBs - resulting in an unprecice Double Value.
Therefore comparing the double values to determine equality is not sufficent for your desired Design of a "Exact Number".
Example:
Long bigLong = 1L<<51; //picked 51: 52 and 53 already causing rounding issues.
Long long1 = bigLong + 1L;
Long long2 = bigLong + 2L;
System.out.println(long1+" -> " + long1.doubleValue());
System.out.println(long2+" -> " + long2.doubleValue());
//false, enough precision to preserve bit "0" and "1".
System.out.println(long1.doubleValue()==long2.doubleValue());
Output:
2251799813685262 -> 2.251799813685262E15
2251799813685263 -> 2.251799813685263E15
false
When setting bit 54:
Long bigLong = 1L<<54;
Long long1 = bigLong + 1L;
Long long2 = bigLong + 2L;
System.out.println(long1+" -> " + long1.doubleValue());
System.out.println(long2+" -> " + long2.doubleValue());
System.out.println(long1.doubleValue()==long2.doubleValue());
Output:
18014398509481985 -> 1.8014398509481984E16
18014398509481986 -> 1.8014398509481984E16
true
Note the Exponent beeing increased from 15 to 16, which will cut off the difference of "1" between both longs.
To solve this, you can compare left1 to left2 and right1 to right2 without converting it to a double.
Your equal method should ideally test every necessary value in your class. In this case, it should be checking to see if your left and right values are the same between the two objects. If they are the same, then you can consider the objects to be equal.
In your case, you should probably put a debug point in your equals method to see why the function is returning back a false.
Try using Eclipse's built in functionality to create equals and hashcode methods for you. You can create that by going to Source->Generate hashCode() and equals(). The methods will be very different from what you have created.
Another thing, in your AssertEquals method, make sure both the values passed in are of the same type. In your case, you're checking a Double with an ExactNumber object. They will definitely not be the same. You need to either
Change your Add method to return a ExactNumber object
Have a method in your ExactNumber class called getDouble() and use that as the second parameter instead.
Hope this helps.
Related
I am working on a problem that seems to require backtracking of some sort. I have a working recursion method but stackOverFlow happens with larger inputs. Could this be solved with an iterative implementation? I am trying to implement a method that takes in two target values a and b. starting with a = 1 and b = 1, how many "adds" would it take to reach the target a and b values? adds can either make a = a + b or b = b + a, but not both.
for example, if target a = 2 and target b = 1, it takes 1 "add". a=1 & b=1, a = a + b = 2.
public static String answer(String M, String F) {
return answerRecur(new BigInteger(M), new BigInteger(F), 0);
}
public static String answerRecur(BigInteger M, BigInteger F, int its) {
if(M.toString().equals("1") && F.toString().equals("1")) {
return "" + its;
}
else if(M.compareTo(new BigInteger("0")) <=0 || F.compareTo(new BigInteger("0")) <=0) {
return "impossible";
}
String addM = answerRecur(M.subtract(F), F, its +1);
String addF = answerRecur(M, F.subtract(M), its +1);
if(!addM.equals("impossible")) {
return addM;
}
if(!addF.equals("impossible")) {
return addF;
}
return "impossible";
}
Recursive backtracking works by going through all candidate steps, do a step, recurse, undo the step.
This means that if a solution takes N items, ideally the recursion depth will not exceed N.
So: an overflow is not expected, probably too much is tried, or even infinitely recurring.
However in your case a BigInteger might be sufficient large and when using small steps (1) one would have a very recursion depth. And every call creates sufficient much. Better would be int or long instead of BigInteger.
In every call you have two candidates:
M.subtract(F)
F.subtract(M)
You evaluate both, one could stop when a result was found.
Also intelligence (of the math!) is missing: nice would be to prevent too many steps, finding as directed as possible a solution. In general this can be achieved by some way of sorting of the (2) candidates.
How one comes at a smart solution? First the math must be readable, what BigInteger is less. Try some sample solutions by hand, and look for a smart approach to order the attempts.
You can cut the recursion short, assuming keeping M and F positive:
if (M.compareTo(BigInteger.ZERO) <= 0 || F.compareTo(BigInteger.ZERO) <= 0) {
return "impossible";
}
if (M.equals(BigInteger.ONE)) {
return String.valueOf(F.intValue() - 1 + its);
}
if (F.equals(BigInteger.ONE)) {
return String.valueOf(M.intValue() - 1 + its);
}
The same can be done with integer division (and modulo):
if (M.compareTo(F) > 0) {
String addM = answerRecur(M.mod(F), F, its + M.divided(F).intValue());
}
Thinking of an iterative solution actually is possible here despite more than one recursive call, but it would not add to the quality.
Remarks:
by java convention one should use f and m for variable names.
is BigInteger really required? It causes a bit awkward code.
Still learning and I cant seem to wrap my head on what seemed like an easy task.
The computeMethods method's is where im totaly stumped, however the reverse method i just keep getting back the same integer without it being reversed.
/****************************
* For Method Computemethods1 i must compute series
* b(x)=1/3+2/5+3/7..... +x/2x+1
* For method ComputeMethod2
* 1/2+2/3+......... x/(x+1)
*******************************/
public static int computeMethod1(int x){
if (x==0)
return 0;
if (x==1)
return 1;
return computeMethod1(x-1/3/(x-1))+computeMethod1(x-2/3/(x-2));
}
public static int computeMethod2(int x){
if (x==0)
return 0;
return computeMethod2((x-1)/(x-1)+1)+computeMethod2((x-2)/(x-2)+1);
}
/********************
* For method reverseMethod i must reverse a user given int
**********************/
public static int reverseMethod(int x){
int reversedNum=0;
if (x!=0)
return x;
reversedNum=reversedNum *10 +x%10;
return reversedNum+reverseMethod(x/10);
}
/******************
* For method sumDigits i must use recursion
* to sum up each individual number within the int
********************/
public static long sumDigits(long n){
if( n==0)
return 0;
if (n==1)
return 1;
else
return n+sumDigits(n-1);
}
}
For reverse method, you are using: if (x!=0) return x;
May be you need to use: if (x==0) return x. So the logic is, if the given argument is 0, then return 0, else return reversed number.
P.S.: As somebody mentioned in comentaries, please take care of types, so for the division you are better using float or double, and take care of operations precedence for correct result, so (x+1)/2 will be different from x+1/2.
For each of your methods, follow through your code for small x.
For example, computeMethod1 should return:
1/3 for x == 1, whereas at the moment it simply returns 1 (Note, the return type will need to be something other than int.).
1/3 + 2/5 for x == 2.
1/3 + 2/5 + 3/7 for x == 3.
For each x, notice how we can use the previous result i.e. computeMethod1(x - 1).
When you come across code that doesn't seem to do what you expect, make your code simpler and simpler until you can narrow down where the problem is, then hopefully it will be obvious what the problem is, or online documentation can tell you.
Hello and thank you for your time and support.
My generalized question is: How should one roll back in a recursive function where specific values have to be returned?
My specific case:
In this problem, I have to check whether a given polynomial has any roots in a given interval, defined by it's margins: x1 and x2.
I have to do this by continuously halving the interval [x1,x2] until the difference between them is at most a value close to zero (for this value, I used the foundroot variable), in which case a root has been found.
This process is done by the recursive findaroot method with parameters x1 and x2 (the interval margins).
Here is how the method works:
The method first checks whether the value for f(x1) and f(x2) (the function's values in x1 and x2) have the same sign, in which case, there is no root in the interval, and returns the noroot value;
Then , it checks whether a root has been found (if x1-x2<=foundroot);
If a root has not been found, it returns minimum between the returned values for one of the intervals, noroot being a very high number in my case. Of course, this doesn't work if a root exceeds the value of noroot.
My question is:
As the generalized question states, how should I make the method work for all cases, other than comparing the returned value with a high/low/not-easily-obtained number?
Here is my written code:
//found root variable + value assigned if root is not found in interval (x1,x2)
static final double foundroot = 0.000001;
static final double noroot=999999;
//finds root
static double findaroot(double x1, double x2)
{
if( Math.signum( f(x1,0) ) == Math.signum( f(x2,0) ) )
{
return noroot;
}
else
{
if(Math.abs(x1-x2)<=foundroot)
{
return x1;
}
else
{
return Math.min( findaroot(x1,(x1+x2)/2) , findaroot((x1+x2)/2,x2));
}
}
}
If there's anything unclear, please ask. If you believe my questions/title are unspecific or unclear, please tell me how to modify them.
I will make clarifications as best I can to provide a clear description and, hopefully, a clear answer.
Thank you!
Using a magic number (no root), can be avoided by using a meaningful return value. In this case, you could consider switching to Double instead of double, and using the null value as a "no result" indicator.
This can be applied generically: If you are using recursive functions to calculate a certain outcome, but need to escape as well, using the null value is an acceptable escape. You could consider compound answers as well in case you need more than 1 escape (e.g. the reason for deciding no answer can be found). Use an object to construct your result in that case.
So in this case, alter your function to e.g.
static final double threshold = 0.000001;
//finds root; returns null if none is found
static Double findaroot(double x1, double x2)
{
if( Math.signum( f(x1,0) ) == Math.signum( f(x2,0) ) )
{
return null;
}
else
{
if(Math.abs(x1-x2)<=threshold)
{
return x1;
}
else
{
return Math.min( findaroot(x1,(x1+x2)/2) , findaroot((x1+x2)/2,x2));
}
}
}
Qn (from cracking coding interview page 91)
Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated.
My question is: Why is it that if maxHeap is empty, it's okay to return minHeap.peek() and vice versa in getMedian() method below?
Doesn't this violate the property of finding a median?
I am using the max heap/min heap method to solve the problem. The solution given is as below:
private static Comparator<Integer> maxHeapComparator, minHeapComparator;
private static PriorityQueue<Integer> maxHeap, minHeap;
public static void addNewNumber(int randomNumber) {
if (maxHeap.size() == minHeap.size()) {
if ((minHeap.peek() != null)
&& randomNumber > minHeap.peek()) {
maxHeap.offer(minHeap.poll());
minHeap.offer(randomNumber);
} else {
maxHeap.offer(randomNumber);
}
} else {
if (randomNumber < maxHeap.peek()) {
minHeap.offer(maxHeap.poll());
maxHeap.offer(randomNumber);
} else {
minHeap.offer(randomNumber);
}
}
}
public static double getMedian() {
if (maxHeap.isEmpty()) {
return minHeap.peek();
} else if (minHeap.isEmpty()) {
return maxHeap.peek();
}
if (maxHeap.size() == minHeap.size()) {
return (minHeap.peek() + maxHeap.peek()) / 2;
} else if (maxHeap.size() > minHeap.size()) {
return maxHeap.peek();
} else {
return minHeap.peek();
}
}
The method has a shortcoming that it does not work in situations when both heaps are empty.
To fix, the method signature needs to be changed to return a Double (with the uppercase 'D') Also a check needs to be added to return null when both heaps are empty. Currently, an exception on a failed attempt to convert null to double will be thrown.
Another shortcoming is integer division when the two heaps have identical sizes. You need a cast to make it double - afetr all, that was the whole point behind making a method that finds a median of integers return a double in the first place.
Another disadvantage with this approach is that it doesn't scale well, for example to heap sizes that don't fit in memory.
A very good approximation algorithm is simply storing an approximate median with a fixed increment (eg. 0.10), chosen appropriate to the scale of the problem. For each value, if the value is higher, add 0.10. If the value is lower, subtract 0.10. The result approximates the median, scales well, and can be stored in 4 or 8 bytes.
Just do this ... else everything is correct:
return new Double(minHeap.peek() + maxHeap.peek()) / 2.0;
The following simple code in Java contains hardly 3 statements that returns unexpectedly false though it looks like that it should return true.
package temp;
final public class Main
{
public static void main(String[] args)
{
long temp = 2000000000;
float f=temp;
System.out.println(f<temp+50);
}
}
The above code should obviously display true on the console but it doesn't. It displays false instead. Why?
This happens because floating point arithmetic != real number arithmetic.
When f is assigned 2000000000, it gets converted to 2.0E9. Then when you add 50 to 2.0E9, its value doesn't change. So actually, (f == temp + 50) is true.
If you need to work with large numbers but require precision, you'll have to use something like BigDecimal:
long temp = 2000000000;
BigDecimal d = new BigDecimal(temp);
System.out.println(d.compareTo(new BigDecimal(temp+50)) < 0);
Will print true as one would expected.
(although in your case I don't know why you'd need to use a datatype other than long).