I do not understand recrusive methods - java

public static double calculatePower (double x, int y) {
if (y == 0)
return 1;
else
return (int) calculatePower(x, y-1);
I understand how the recrusive function is called, but not how it is cancelled.
I think, if at some point y=1 the function should return 1 because of the if statement.
But it does not and I do not understand why

For every recursive invocation the incoming y parameter is reduced by one since you write calculatePower(x, y-1);. At some point y is 0 and the recursion stops.
Note that your power calculation is wrong , you should add a x * before the actual recursive call: x * calculatePower(x, y-1)

This will subtract 1 from y every time it gets executed.
I recommend you execute it manually on paper to see how the program works.
ex: calculatepower(2,3) -> calculatepower(2,2) -> calculatepower(2,1) -> calculatepower(2,0). Now since y = 0 the if statement will get executed and it will return 1
Your function will only return the value 1 though (if y was a positive number)
This youtube tutorial will give you a clear explanation for recursion:
https://www.youtube.com/watch?v=neuDuf_i8Sg

Related

Java finding Zero Points with Newton Algorithm endless loop

I'm havinga Problem with a method, which takes a Polynom like f(x)=x²+1 and calculates possible zero points with the newton algorithm.
I have given requirements for specific variables so even if the naming is not good or a variable is not needed I have to use them :/
The Polynom I give my method as a parameter is a double-array: For f(x)=x²+1 it would be {1.0,0.0,1.0}
so its constructed like 1.0*x^0 + 0.0*x^1+1.0*x^2
For my Code:
x0 is the start value for the newton algorithm and eps is for the accuracy of the calculation
I followed my given Instructions and got the following code working:
public static double newton(double[] a, double x0, double eps) {
double z;
double xn;
double xa = x0;
double zaehler;
double nenner;
do {
zaehler = horner(a, xa);
nenner = horner(ableit(a), xa);
if(nenner == 0) {
return Double.POSITIVE_INFINITY;
}
xn = xa - (zaehler/nenner);
xa = xn;
} while((Math.abs(horner(a, xn))) >= eps);
z = xn;
return 0;
}
the method horner() calculates the y-Value of a given function for a given x-Value.
My Problem is if the Function doesn't has a zero-point like x²+1 and I start with x0=1 and eps=0.1 I get Infinity returned.
But If I start with x0=10 and eps=0.1for example I create an endless loop.
How can I deal with this or is this a general Problem with the Newton Algorithm?!
Is the only way to set a fixed maximum of Iterations?
The Code is working for Polynoms that have at least one zero-point!
The Newton–Raphson method requires the existence of a real root x such that f(x)=0. The function you use x^2+1 has no real roots, so your algorithm will not work in this case (nor in others where there is no root).
Since x^2+1 >= 1 for all real x this implies horner(a, xn) >= 1, so the loop
while((Math.abs(horner(a, xn))) >= eps)
will not terminate for eps < 1.
Maybe before starting to iterate, you should check the existence of a zero.
E.g. if the highest (according to the power of x) nonzero coefficient is odd then there will be a real zero.
Or extend your algorithm such that it previously tries to find some real aand b such that f(a)f(b) <= 0 (then between a and b there is a root).

Representing the equation of a line in a variable in Java

I don't think I need code here, but just so you can see what I'm looking at:
public class Valuation {
//line is a monotonic (non-decreasing. Could be constant at points)
//line in 2D space where x=0 -> y=0 and x=1 -> y=1
//the gradient cannot be infinite
//line is only defined between x=0 and x=1. Can catch when arguments to
//functions are unacceptable given this.
LineEquation line;
float cut(float from, float value){
//Using 'from' as x, return the least value x' where 'value' is the difference
//between the y value returned by x and the y value returned by x'
}
float eval(float from, float to){
//require to > from
//return the difference between the y value returned by 'to'
//and the y value returned by 'from'
}
The question I have is how do I represent a line/curve like this in Java? I can verify the lines given fit the requirements that I have, but I want to have this LineEquation class to be able to handle essentially any line that fits these requirements. These could be quadratic curves or lines where we have something like, when x is between 0 and 0.5, the equation is a, and then when x is between 0.5 and 1, the equation is b. I got frustrated thinking of all the ways you could describe a line that meets the specifications, and then how I would go through them all, and how I would have to deal with all the different types in different ways. Unfortunately I do not have the vocabulary to find a library that has what I want.
If you're using Java 8, then probably the simplest thing to do would be to store the curve as a Function<Float,Float>, which can implement any kind of equation for any kind of curve, provided y is single-valued for any given x, and x always falls within range for a float.
Your class might look like this.
public class Valuation {
final Function<Float,Float> curve;
public Valuation(final Function<Float,Float> curve) {
this.curve = curve;
}
float eval(float from, float to){
return curve.apply(to) - curve.apply(from);
}
}
Then you can create these with calls such as
new Valuation( x -> ( x * x + 2 * x + 3 ))
for a typical monotonic quadratic, or
new Valuation( x -> ( x > 0.5 ? 3 * x : 1 + x ))
for a piecewise function consisting of two linear sections.
I haven't shown the code for cut. Had to leave something up to you!

Two parallel increment and decrement terminating when equal

Let's say you have the following two procedures:
var x = 0;
var y = 10;
def P = { while (x != y) x = x + 1; }
def Q = { while (x != y) y = y - 1; }
Run both in parallel.
The only atomic operations are READ, INCREMENT, DECREMENT, WRITE.
I would imagine there is a case where one process "skips over" the other (since you don't control how they are run).
Here is an example:
P and Q READ x = 0, y = 10 (the very beginning)
Q runs quickly and makes y reach 0
P INCREMENTS and WRITES and now x is 1 (since it still thinks y is 10)
back to Q, READ x as 1 and y as 0
Q decrements y to -1
Never terminate
Why doesn't that happen? it seems like it ALWAYS terminates.
Can someone explain why my example doesn't happen?
I was first going to downvote this question but it gave me mixed feelings because on one hand it's not a well phrased question: what concurrency framework do you use? Are you sure you are doing the right thing - is it truly concurrent? How can we tell without seeing more code. What are these assumptions about atomicity? Do you physically run this on a single thread in some sort of VM where there is no true concurrency? How do I know all this? Are you really running only until a count of 10? Do I even care? Should I care? ...
... but then I though I should point this out:
Does this loop terminate?:
var x = 1; while(x>0){ x = x + 1 }
Or a similar question - what's the value of Int.MaxValue + 1?
That's a partial answer to your question... the other part I don't quite care about ;)
I like your question in general, but you have to provide the real soure code so that we can help. One possible answer is optimization. Value of y in the P loop can be "cached" in a processor register and doesn't have to contain current value from memory.
In Java you can solve this issue by the volatile keyword:
http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
In Scala there is a volatile annotation:
http://www.scala-lang.org/old/node/7952.html
Try to add println(y) to the P loop so that you see whether (and how) value of y changes. Keep on trying.

Is it possible to find out which number is bigger without using an if statement?

I'm doing some small program for a beginners programming course and in my program I have 2 variables which hold numbers. Anyway I need to find out which number is bigger and print the appropriate message according to it, for example I have:
int x = 5;
int y = 10;
I need to print:
"it is true that y is bigger than x";
Now the thing is that I know I can use a simple if statement but I'm not allowed to use it, now it makes me wonder, is it even possible? If so, how can I do that? How can I check which number is bigger WITHOUT doing something like:
if (x > y)
answer = true;
...
Thanks in advance.
Well you can do:
boolean answer = x > y;
The expression x > y is just an expression of type boolean. While boolean expressions are often used for conditions in if statements, loops etc, they don't have to be - simple assignment works fine too.
It sounds like you want the reverse though:
boolean answer = y > x;
Then you can use the value of answer to build the string to display...
Use the ternary operator:
System.out.println(x > y ? "It is true that x is greater than y" : "");
ternary operator "?:"
String output = (x > y)? "x is greater than y":"y is greater than x";
The ternary conditional operator that others mentioned will work. Assuming you are looking for creative ways to do this rather than practical ones, here's another method:
int x = 5;
int y = 10;
while(y > x){
System.out.println("It is true that y is bigger than x.");
return;
}
System.out.println("It is false that y is bigger than x.");
The while is just acting as a fancy if, because the return means the otherwise infinite loop will only execute at most once.
Here's another example that instead relies upon short-circuit boolean evaluation:
public static void main(String...args){
int x = 5;
int y = 10;
boolean answer = (y > x);
boolean testTrue = answer && printTrue();
boolean testFalse = testTrue || printFalse();
}
private static boolean printFalse() {
System.out.println("It is false that y is bigger than x.");
return true;
}
private static boolean printTrue() {
System.out.println("It is true that y is bigger than x.");
return true;
}
Of course you shouldn't do this in real production code, but it can be fun to think of unorthodox ways to code something and it can be helpful for exploring the language.
Your question is tagged as Java but you do not specify Java in your question. In Java there are multiple ways to get the same result that involve testing the boolean expression x > y somehow, such as the ternary operator. I would consider these equivalent to an explicit if statement.
Other possibilities:
Compute the square root of x - y. This will raise an exception if y is bigger. Catch the exception in the caller and report that y is the larger quantity. If there is no exception, report that x is the larger.
In LISP, Ruby or another language that supports the symbol type, form a list ((symbol x, x), (symbol y, y)) and sort the list. Then report the second symbol as the variable with the larger value.
If using assembly, BASIC, PL/1, etc. you can use an arithmetic expression to choose the target of a GOTO statement. Depending on whether x or y is larger, execution will resume at a different part of the code. Or use the list-sorting trick in the previous bullet to select the GOTO label.
In general, the expression ((x - y) / abs(x - y) + 1) / 2 will produce 1 if x is larger and 0 if y is larger. This result could be used to choose data, a function, etc. out of a list of two alternatives, producing conditional behavior without an if statement.
You could use recursion (but I would not recommend it)
public int compare ( int a , int b )
{
switch ( a )
{
case Integer.MIN_VALUE :
switch ( b )
{
case Integer.MIN_VALUE :
return 0 ;
default :
return -1 ;
}
default :
switch ( b )
{
case INteger.Min_VALUE :
return 1 ;
default :
return compare ( a-1 , b-1 ) ;
}
}
}
(a+b)/2 + Abs(a-b)/2 is the bigger number.
I know in some languages you can use short-circuit evaluation to construct the answer.
The expression (A && B) always evaluates to B if A is true. If A is false then B is never evaluated.
Similarly (A || B) evaluates to B if A is false. If A is true B is never evaluated.
Though I'm not 100% sure of Java, the expression you want is:
String output = ((x > y) && "it is true that X is greater than Y")
|| (((x < y) && "it is true that X is less than Y")
|| "it is true that X is equal to Y");

How to code a selector?

I am working on a algorithm but there is a note about a selector. I am not sure what this means but the research paper I am working says:
δ () is a selector, i.e. δ (x) =1 if x>0, else
δ (x) = 0 ;
How does one code this using pseudo code, c++, or Java?
Thanks
δ () is a selector, i.e. δ (x) =1 if x>0, else δ (x) = 0
You just need an if
In pseudocode:
delta = function(x)
{
if (x > 0)
return 1
else
return 0
}
this is a function
pass in x
check if x > 0
if so, return 1
otherwise
return 0
template <class T>
int selector(T x)
{
return x > 0 ? 1 : 0;
}
A selector in this context is simply a boolean function which returns 0 (or 1) for all values of x up to a certain point, and then return 1 (or 0) there after. In other words, a two-steps step function.
BTW, given the specific definition of delta in the question, delta is the discrete Heaviside Step Function with a value of 0 for x = 0.
If you don't want to use an if, you could write (in C#):
Math.Ceiling(Math.Sign(x) * 0.1)
In Java it should be something like this:
Math.ceiling(Math.signum(x) * 0.1)

Categories