how to implement pow(double x, double y)? - java

I know how to impelment pow(double x, int y)
public class Solution {
public double myPow(double x, int n) {
if (n == 0)
return 1;
if (n % 2 == 0) {
return myPow(x * x, n / 2);
} else {
if (n > 0)
return x * myPow(x, n - 1);
else
return 1 / x * myPow(x, n + 1);
}
}
}
But how to make it handle double y?

Exponentiation with non-integer values is done mathematically with infinite series:
See here under "Exponential Series Expansion" and "Exponential Theorem"
Basically, you'll use a known infinite series of terms, and calculate a number of them that satisfies your numerical precision requirements.

If i recall correctly you need to write a series expansion for log (natural logarithm) and exp (exponent).Sincelog(x^y) = y*log(x) andexp(log(x)) = xyou can evaluate the result. I think I used the Taylor series for this.wikipedia

Related

StackOverFlow Error For Problem Number 50 in Leetcode

For the below Input I am getting a StackOverflow error. Can u guys help me with an explanation and how to solve this problem in my code.
System.out.println(myPow(0.00001,2147483647));
public static double myPow(double x, int n) {
return helperPow(x,n,1);
}
private static double helperPow(double x, int n,double d) {
if(n == 0) {
return d;
}
if(n < 0) {
return helperPow(x,++n, d/x);
}
return helperPow(x, --n, d*x);
}
Using your current approach, the number of levels of recursion will be equal to n, so it will definitely cause a StackOverflow exception as it requires considerable stack space.
Note that if n is an even number, x^n = (x ^ (n/2)) * (x ^ (n/2)).
If n is an odd number, x^n = (x ^ (n/2)) * (x ^ (n/2)) * x.
So you can reduce the number of levels of recursion to log(n), which will definitely not cause a Stackoverflow exception even if n is large (In your case, n is 2147483647, it will take 31 recursions):
public double myPow(double x, int n) {
return n >= 0 ? helperPow(x, n) : 1.0 / helperPow(x, -n);
}
public double helperPow(double x, long n) {
if (n == 0) {
return 1.0;
}
double y = helperPow(x, n / 2);
return n % 2 == 0 ? y * y : y * y * x;
}

Sin taylor series recursive approximation

I need some insight on my recursive method of calculating the sin Taylor series, which doesn't work properly. The method calls two other recursive methods which are a recursive pow method and a recursive factorial method. I compared my findings with an iterative sin method giving me the correct solution. What is missing in my recursive sin method ?
Approximation of sin(x)= x - x^3/3! + x^5/5! -x^7/7!+ ...
public class SinApprox
{
public static void main (String [] args)
{
Out.println(sinx(1, 1, 2, 1, 1, 0, 1));
Out.print(sinIT(2));
}
static double sinIT(double x)
{
double sin = 0;
double a = x;
double b = 1;
double term = a/b;
double vz = 1;
double i = 1;
while(term > 0.000001)
{
i = i +2;
sin = sin + (term*vz);
a= rekursivPow(x,i);
b = rekursivN(i);
term = a/b;
vz = -1 * vz;
}
return sin;
}
static double rekursivN(double n)
{
if(n==1)
{
return 1;
}
return n * rekursivN(n-1);
}
static double rekursivPow(double x , double y)
{
if(y == 1)
{
return x ;
}
return x * rekursivPow(x , y - 1);
}
static double sinx(double i ,double n, double x, double y, double vz, double sum, double pow)
{
double term = pow / n;
if(term > 0.000001)
{
sum = sum + (term * vz);
vz = -1 * vz;
i = i +2;
n = rekursivN(i);
y = y +2;
pow = rekursivPow(x ,y);
return sinx(i, n, x , y , vz, sum, pow);
}
return sum;
}
}
Step one would be to write out the function in a way that makes the recursive relationship clear (you can't write code for what isn't clear) so, don't start with this:
sin(x)= x - x^3/3! + x^5/5! -x^7/7!+ ...
But instead, ask "how can I make all those terms with x look the same":
sin(x)= x^1/1! - x^3/3! + x^5/5! + ...
Good start, but if we're recursing, what we're really looking for is something that only computes one of those terms, and then calls itself with updated arguments to compute the next term. Ideally, we want something like:
doThing(args) {
return simpleComputation() + doThings(updatedargs);
}
And then recursion does the rest. So let's first make sure that we only ever have to deal with + instead of a mix of + and -:
sin(x)= (-1)^0 * x^1/1! + (-1)^1 * x^3/3! + (-1)^2 * x^5/5! + ...
And now you have something you can actually express as a recursive relation, because:
sin(x,n) {
return (-1)^n * x^(2n+1) / (2n+1)! + sin(x, n+1);
}
With the "shortcut" function:
sin(x) {
return sin(x,0);
}
And that's where the hints stop, you should be able to implement the rest yourself. As long as you remember to stop the recursion because a Taylor series is infinite, and computer programs and resources are not.

Recursive method for x^n optimised for when n is even

I need to write a recursive method using Java called power that takes a double x and an integer n and that returns x^n. Here is what I have so far.
public static double power(double x, int n) {
if (n == 0)
return 1;
if (n == 1)
return x;
else
return x * (power(x, n-1));
}
This code works as expected. However, I am trying to go the extra mile and perform the following optional exercise:
"Optional challenge: you can make this method more efficient, when n is even, using x^n = (x^(n/2))^2."
I am not sure how to implement that last formula when n is even. I do not think I can use recursion for that. I have tried to implement the following, but it also does not work because I cannot take a double to the power of an int.
if (n%2 == 0)
return (x^(n/2))^2;
Can somebody point me in the right direction? I feel like I am missing something obvious. All help appreciated.
It's exactly the same principle as for x^n == x*(x^(n-1)): Insert your recursive function for x^(n/2) and (...)^2, but make sure you don't enter an infinite recursion for n == 2 (as 2 is even, too):
if (n % 2 == 0 && n > 2)
return power(power(x, n / 2), 2);
}
Alternatively, you could just use an intermediate variable:
if (n % 2 == 0) {
double s = power(x, n / 2);
return s * s;
}
I'd probably just handle 2 as a special case, too -- and avoid the "and"-condition and extra variable:
public static double power(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
if (n == 2) return x * x;
if (n % 2 == 0) return power(power(x, n / 2), 2);
return x * (power(x, n - 1));
}
P.S. I think this should work, too :)
public static double power(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
if (n == 2) return x * x;
return power(x, n % 2) * power(power(x, n / 2), 2);
}
When n is even, the formula is exactly what you wrote: divide n by two, call power recursively, and square the result.
When n is odd, the formula is a little more complex: subtract 1 from n, make a recursive call for n/2, square the result, and multiply by x.
if (n%2 == 0)
return (x^(n/2))^2;
else
return x*(x^(n/2))^2;
n/2 truncates the result, so subtraction of 1 is not done explicitly. Here is an implementation in Java:
public static double power(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
double pHalf = power(x, n/2);
if (n%2 == 0) {
return pHalf*pHalf;
} else {
return x*pHalf*pHalf;
}
}
Demo.
Hint: The ^ operation won't perform exponentiation in Java, but the function you wrote, power will.
Also, don't forget squaring a number is the same as just multiplying it by itself. No function call needed.
Making a small change to your function, it will reduce the number of recursive calls made:
public static double power(double x, int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return x;
}
if (n % 2 == 0) {
double temp = power(x, n / 2);
return temp * temp;
} else {
return x * (power(x, n - 1));
}
}
Since
x^(2n) = (x^n)^2
you can add this rule to your method, either using the power function you wrote, as Stefan Haustein suggested, or using the regular multiplication operator, since it seems you are allowed to do that.
Note that there is no need for both the base cases n=1 and n=0, one of them suffices (prefferably use the base case n=0, since otherwise your method would not be defined for n=0).
public static double power(double x, int n) {
if (n == 0)
return 1;
else if (n % 2 == 0)
double val = power(x, n/2);
return val * val;
else
return x * (power(x, n-1));
}
There is no need to check that n>2 in any of the cases.
This just reminds me more optimisation could be done
and this following code.
class Solution:
# #param x, a float
# #param n, a integer
# #return a float
def pow(self, x, n):
if n<0:
return 1.0/self.pow(x,-n)
elif n==0:
return 1.0
elif n==1:
return x
else:
m = n & (-n)
if( m==n ):
r1 = self.pow(x,n>>1)
return r1*r1
else:
return self.pow(x,m)*self.pow(x,n-m)
what is more intermediate result could be memorised and avoid redundant computation.

Recursive "Power Of" function

We are given an assignment to solve a recursive function that can calculate the power of a number using the following rules (took a snapshot):
http://i.imgur.com/sRoQJ1j.png
I cant seem to figure out to do this as I have been trying for the past 4 hours.
My attempt:
public static double power(double x, int n) {
if(n == 0) {
return 1;
}
// x^n = ( x^n/2 )^ 2 if n > 0 and n is even
if(n % 2 == 0) {
double value = ((x * power(x, n/2)) * x);
return value;
} else {
double value = x * ((x * power(x, n/2)) * x);
return value;
}
}
I believe I am doing wrong when I am multiplying x with the recursive function whereas I should be multiplying by x (power Of = x * x * .... x(n))...
I also can see that in this statement:
double value = ((x * power(x, n/2)) * x);
It is wrong because I am not squaring the value but just multiplying it with x. I think I need to store it in a variable first, then do something like value * value to square the end result - but that just gives me a huge number.
Any help is appreciated, thanks.
The problem is in this statement:
if(n % 2 == 0) {
double value = ((x * power(x, n/2)) * x);
return value;
It is both syntactically (the brackets don't match) as semantically (deeper recursion, incorrect).
It should be replaced with:
if(n % 2 == 0) {
double value = power(x*x, n/2);
return value;
The reason is that:
x^(2*k) = (x^2)^k
Which is almost literally what is implemented in the code. Because we know n is even, there is a k = n/2, such that the above equation holds.
The same with the odd case:
else {
double value = x * power(x*x, n/2);
return value;
This because:
x^(2*k+1) = x*x^(2*k) (version of #rgettman)
With k = (n-1)/2, which can be further optimized to:
x^(2*k+1) = x*x^(2*k)=x*(x^2)^k (our version)
You can further optimize this as:
public static double power(double x, int n) {
if(n == 0) {
return 1;
}
double xb = x*x;
if((n&0x01) == 0x00) {
return power(xb,n>>>0x01);
} else {
return x*power(xb,n>>>0x01);
}
}
Or, you could transform the recursive aspect into a while algorithm (since it is mainly tail-recursion:
public static double power(double x, int n) {
double s = 1.0d;
while(n != 0) {
if((n&0x01) != 0x00) {
s *= x;
}
n >>>= 0x01;
x *= x;
}
return s;
}
Performance:
three different versions were implemented. This jdoodle shows benchmark tests. With:
power1 the version of #rgettman;
power2 the proposed recursive version in this answer; and
power3 the non-recursion version.
In case one sets L to 10'000'000 (thus calculating all power from 0 up to L), one run results in:
L = 10M L=20M
power1: 1s 630 018 699 3s 276 492 791
power2: 1s 396 461 817 2s 944 427 704
power3: 0s 803 645 986 2s 453 738 241
Don't take the numbers after the comma very seriously. Although Java measures in nano-seconds, these numbers are extremely inaccurate and have more to do with side-events (like OS calls, cache-faults,...) than with the real program runtime.
In your "even" case, you can calculate it with the recursive call, passing n/2 as you've done. But you need to multiply the result with itself to square it.
double value = power(x, n/2);
value *= value;
return value;
In your "odd" case, you can multiply x by the recursive call of the exponent minus 1.
double value = x * (power(x, n - 1));
return value;
You need to understand how recursion works internally. Logic is simple is to store the function calls and returned values in a stack. When the method termination condition is reached, pop out the values and return from method.
You need simply this:
public static double power(double x, int n) {
if(n == 0) {
return 1;
} else {
double value = (x * power(x, (n-1)));
return value;
}
}

How to use recursion to round a decimal to the nth place

I have a comp sci question that requires the following:
Write a method that takes a decimal number x and an integer n. Round x to n decimal places (for example, 0 means round to the nearest integer, 1 means round to the nearest tenth, etc.).
I don't see how this problem is even approachable using recursion, it seems too straight forward.
It seems that using recursion here is simply counter-productive.
The recursive method suggested by nullptr:
double round(double x, int n) {
if (n <= 0)
return Math.round(x);
return round(x * 10, n - 1) / 10;
}
is valid, but unnecessary. Essentially, that method is the same as:
double round(double x, int n) {
double factor = Math.pow(10, n);
return Math.round(x * factor) / factor;
}
This method would likely execute faster and would not risk a StackOverflowError (although that would be fairly unlikely, only with huge values of n).
You should use recursion for cases with a clear base case and simplification case, such as:
traversing a tree:
base case: no children
simplification case: each child
the factorial function:
base case: n <= 1
simplification case: factorial(n-1)
Rounding to n decimal places does not lend itself to recursion easily.
BONUS: Rounding to the nearest n th-fractional part in any base:
double round(double x, int n, int radix) {
double factor = Math.pow(radix, n);
return Math.round(x * factor) / factor;
}
How about this?
double round(double x, int n)
{
if (n <= 0)
return Math.round(x);
return round(x * 10, n - 1) / 10;
}
You'll have to adapt this a little if you can't use Math.round().
i used recursion and parsing, however i think there are some logical holes.
public static double problem3(double x, int y)
{
// Trying to take the double, turn it into a string, manipulate past the decimal
// probably not the most efficient method..
String P = Double.toString(x).substring(0, Double.toString(x).length()-1);
String k =P.substring(P.indexOf('.')+ 1,P.length());
if (k.length()==y)
{
if (P.charAt(P.length()-1)<5)
{
return Double.parseDouble(P);
}
else
{double o7 = Double.parseDouble(P)*Math.pow(10, k.length());
o7++;
o7=o7/Math.pow(10, k.length());
return o7;
}
}
else
{
return problem3(Double.parseDouble(P),y);
}
}

Categories

Resources