The golden ratio in java - java

Consider the sequence X1=1, X2= 1+1/1, X3= 1+1/1+1/1... . In this sequence Xn+1 = 1+1/Xn (for n>= 1). Write a method in Java that computes Xn. As n increases, the terms of this sequence get closer and closer to the golden ratio 1+sqrt 5/ 2 ~ 1.61803398875. How close is X10 to the golden ratio?
This is the program that I have written but when I run it in java it does not compile. I do not know what to do and it is due tomorrow. Please help!
public class Golden Ratio
{
public static final double GOLDEN = ( 1 + Math.sqrt(5))/2;
/**
* precondition: Class(Golden Ratio), n values
* precondition: sequence values found
*/
public static double sequence (int n)
{
if (n == 0) {
return 1;
{
public static void main(String[] args)
{
for (int n = 0; n < 40; n++)
{
double diff = Math.abs(sequence(n) - GOLDEN);
System.out.print(n+1+")");
System.out.print(n + 1 < 10 ? " seq " + sequence(n): "seq " + sequence (n))
System.out.print("gld " + GOLDEN);
System.out.print("diff = %.32f\t". diff);
System.out.print("\n");
}
System.out.print("\n");
System.out.print("10)" + "sqe " + sequence(9) + "ln gld + GOLDEN"\t diff = %.32 f\t" + diff);
System.out.print("");
}
}
}

Your function should do all the calculating work. Your main method just calls it and presents the results. Here is how it's structured. You'll still need to do the part that calculates the sequence. Double-check the definition, before you do the work, though. If X3=1 + 1/1 + 1/1, then that's the same as saying X3=3, which is obviously wrong.
public static double calculateSequence(int n) {
double sum=0.0;
for (int i=0; i<n; i++) {
// do your magic
}
return sum;
}
public static void main(String[] args) {
double answer=calculateSequence(10);
System.out.println("%f is off by %f", answer, GOLDEN_RATIO - answer);
}

Related

Stochastic Search to lambda expression

Thanks for all your help and sharing.
My question is in regards of the Stochastic Search. This technique is used to do approximations of data through a defined amount of cicles over a, an in general, mathematical calculation. Please see following code, I tried to reduce it to its minimum. My expectation is to have this code setup as a lambda expression, the for loop, I would like to have the best performance of it. I have some intents but I'm not sure if I got the most of it.
package stochasticsearch;
import java.util.Random;
public class StochasticSearch {
public static double f(double x) {
return -(x - 1) * (x - 1) + 2;
}
public static void main(String[] args) {
final Random random = new Random();
double startPointX = 0;
double max = f(startPointX);
long begin = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
double index = 2 * random.nextDouble();
if (f(index) > max) {
max = f(index);
}
}
System.out.println("Elapsed time: " + (System.currentTimeMillis() - begin));
System.out.println("Maximum value y=f(x) is " + max);
}
}
Thanks, have a nice day.
Your code completes in a little under 23 seconds on my system, and I was able to modify it so that it takes under 2 seconds. Here's what I found:
You're using Random when you could be using ThreadLocalRandom instead; this switch results in a relatively-large speedup.
You're calculating f(index) twice inside your for-loop in certain cases when it should only be computed once per iteration.
Because you're iterating over a large range of values, you could utilize a parallel stream instead; this results in a relatively-large speedup as well.
You're adding 2 to every result in f, so it's better to add it a single time once max has been calculated.
public static double f(double x) {
double y = x - 1;
return -y * y;
}
public static void main(String[] args) {
final ThreadLocalRandom random = ThreadLocalRandom.current();
long begin = System.currentTimeMillis();
double max = IntStream.range(0, 1_000_000_000)
.parallel()
.mapToDouble(i -> f(random.nextDouble() * 2))
.max()
.orElse(f(0)) + 2;
System.out.println("Elapsed time: " + (System.currentTimeMillis() - begin));
System.out.println("Maximum value y=f(x) is " + max);
}

java Sine(x) Taylor Series

Can someone help me for geting out this code of sin(x) Tailor function to get followings:
The first 4 sin(x) Tailor series.
To calculating the sin function using the sum-formel
How to write a method public static double MySinApproximate( double x)?
That is what i get so far, and it has to be in this way!!
import java.lang.Math;
public class mysin {
public static void main(String[] args){
double x= Math.PI;
System.out.println( MySin(x) + "\t \t" + Math.sin(x) + "\n" );
}
public static double MySin(double x){
double sumNeu, sumOld, sum;
int i = 1;
sum = sumNeu = x; // This should calculating the first term Value
do //the loop do will calculating the Tailor Series
{
sumOld = sumNeu;
i++; sum = + sum * x * x / i;
i++; sum = sum / i;
sumNeu = sumOld + sum;
}
while( sumNeu != sumOld);
return sumNeu;
}
} // 11.548739357257745 1.2246467991473532E-16 (as output)
Your loop isn't calculating the Taylor series correctly. (This is really a Maclaurin series, which is the special case of a Taylor series with a = 0.) For the sine function, the terms need to be added and subtracted in an alternating fashion.
sin(x) = x - x3/3! + x5/5! - ...
Your method only adds the terms.
sin(x) = x + x3/3! + x5/5! + ...
Flip the sign of sum on each iteration, by adding the designated line:
do // The loop will calculate the Taylor Series
{
sumOld = sumNeu;
i++; sum = + sum * x * x / i;
i++; sum = sum / i;
sum = -sum; // Add this line!
sumNeu = sumOld + sum;
}
With this change I get a result that is very close:
2.3489882528577605E-16 1.2246467991473532E-16
Due to the inherent inaccuracies of floating-point math in Java (and IEEE in general), this is likely as close as you'll get by writing your own sine method.
I tested an additional case of π/2:
System.out.println( MySin(x/2) + "\t \t" + Math.sin(x/2) + "\n" );
Again, it's close:
1.0000000000000002 1.0
1.I want to write all again like that -
2.I try to writing the first 4 series from sine Taylor and the proximity all together but anyhow doesn't work correctly -
3.i get this output
0.0 0.8414709848078965
0.8414709848078965 0.9092974268256817
0.8414709848078965 0.1411200080598672
0.9092974268256817 -0.7568024953079282
4.How can i get the same accuracy
1.0000000000000002 1.0
and the series of sine(x)?
public class MySin {
public static void main(String[] args){
double y = 0;
y = 4;
for (int i = 1; i<= y; i++){
System.out.println( MySin(i/2) + "\t \t" + Math.sin(i) + "\n" );
}
}
public static double MySin(double x){
double sumNew, sumOld, sum;
int i = 1;
sum = sumNew = x; // This should calculating the first term Value
do //the loop do will calculating the Tailor Series
{
sumOld = sumNew;
i++; sum = - sum * x * x / i; // i did change the sign to -
i++; sum = sum / i;
sum = - sum; // so i don't need this line anymore
sumNew = sumOld + sum;
}
while( sumNew != sumOld);
return sumNew;
}
public static double MySineProximity ( double x) {
while ( x <= ( Math.PI /2 ) )
{
x = 0;
}
return MySin (x);
}
}

Calculate e^x without inbuilt functions in Java

I am a beginner in Java and currently going through the "how to think like a computer scientist" beginners book. I am stuck with a problem in the iteration chapter. Could anyone please point me in the right direction?
When I use math.exp, I get an answer that is completely different from the answer my code obtains.
Note, it's not homework.
Here's the question:
One way to calculate ex is to use the infinite series expansion
ex = 1 + x + x2 /2! + x3/3! + x4/4! +...
If the loop variable is named i, then the ith term is xi/i!.
Write a method called myexp that adds up the first n terms of this
series.
So here's the code:
public class InfiniteExpansion {
public static void main(String[] args){
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the power?");
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: "+myExp(x, power));
}
public static double myExp(double myX, double myPower){
double firstResult = myX;
double denom = 1;
double sum =myX;
for(int count =1;count<myPower;count++){
firstResult = firstResult*myX;//handles the numerator
denom = denom*(denom+1);//handles the denominator
firstResult = firstResult/denom;//handles the segment
sum =sum+firstResult;// adds up the different segments
}
return (sum+1);//gets the final result
}
}
The assignment denom = denom*(denom+1) is going to give a sequence as follows: 1, 1*2=2, 2*3=6, 6*7=42, 42*43=...
But you want denom = denom*count.
Let's say in general we just want to print the first n factorials starting with 1!: 1!, 2!, 3!, ..., n!. At the kth term, we take the k-1th term and multiply by k. That would be computing k! recursively on the previous term. Concrete examples: 4! is 3! times 4, 6! is 5! times 6.
In code, we have
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*i; // Here's the recursion mentioned above.
System.out.println(i+'! is '+a);
}
Try running the above and compare to see what you get with running the following:
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*(a+1);
System.out.println('Is '+i+'! equal to '+a+'?');
}
There are several errors here:
firstResult should start from 1, so that it goes 1+x+x^2 instead of 1+x^2+x^3
As timctran stated you are not calculating the factorial in a correct way.
To wrap up you can simplify your operations to:
firstResult = firstResult * myX / (count+1);
sum += firstResult;
Edit:
- I ran the code and saw that Math.exp(power) is printed instead of Math.exp(x)
- My first item is wrong since sum is initialized to myX.
Why make it complicated? I tried a solution and it looks like this:
//One way to calculate ex is to use the infinite series expansion
//ex = 1 + x + x2 /2! + x3/3! + x4/4! +...
//If the loop variable is named i, then the ith term is xi/i!.
//
//Write a method called myexp that adds up the first n terms of this series.
import java.util.Scanner;
public class InfiniteExpansion2 {
public static void main(String[] args) {
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the value of I?"); // !
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: " + myCalc(x, power));
}
public static double fac(double myI) {
if (myI > 1) {
return myI * fac(myI - 1);
} else {
return 1;
}
}
public static double exp(double myX, double myE) {
double result;
if (myE == 0) {
result = 1;
} else {
result = myX;
}
for (int i = 1; i < myE; i++) {
result *= myX;
}
return result;
}
public static double myCalc(double myX, double myI) {
double sum = 0;
for (int i = 0; i <= myI; i++) { // x^0 is 1
sum += (exp(myX, i) / fac(i));
}
return sum;
}
}
If you want to think like an engineer, I'd do it like this:
keep it simple
break it into pieces
stick closely to the task (like I named the var myI, not myPower - seems clearer to me, for a start - that way you won't get confused)
I hope you like it!
I tried a solution and it looks like this:
public class Fact {
public int facto(int n){
if(n==0)
return 1;
else
return n*facto(n-1);
}
}
}
import java.util.Scanner;
public class Ex {
public static void main(String[] args){
Fact myexp=new Fact();
Scanner input=new Scanner(System.in);
int n=1;
double e=1,i=0,x;
int j=1;
System.out.println("Enter n: ");
n=input.nextInt();
System.out.println("Enter x: ");
x=input.nextDouble();
while(j<=n)
{
int a=myexp.facto(j);
double y=Math.pow(x,j)/(double)a;
i=i+y;
++j;
}
e=e+i;
System.out.println("e^x= "+ e);
}
}

Recursion - Java

I am working on a program where I have to use recursion to calculate the sum of 1/3 + 2/5 + 3/7 + 4/9 + ... + i / (2i + 1). However, I am not sure how to make my program show the term that must be added in order to reach the number enter by the user. For example. If I enter 12, I want to know how many terms of the series [1/3 + 2/5 + 3/7 + 4/9 + ... + i / (2i + 1)] were added to get approximately to the number 12.
What I don't want to get is the sum of inputting 12 which in this case is 5.034490247342584 rather I want to get the term that if I were to sum all numbers up to that term I would get something close to 12.
Any help will be greatly appreciated!
This is my code
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
double number;
Scanner input = new Scanner(System.in);
System.out.println("Enter a value= ");
number = input.nextInt();
System.out.println(sum(number) + " is the term that should be added in order to reach " + number);
}
public static double sum(double k) {
if (k == 1)
return 1/3;
else
return ((k/(2*k+1))+ sum(k-1));
}
}
You have this question kind of inside out. If you want to know how many terms you need to add to get to 12, you'll have to reverse your algorithm. Keep adding successive k / (2k + 1) for larger and larger k until you hit your desired target. With your current sum method, you would have to start guessing at starting values of k and perform a sort of "binary search" for an acceptably close solution.
I don't think that this problem should be solved using recursion, but... if you need to implement it on that way, this is a possible solution:
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
double number;
Scanner input = new Scanner(System.in);
System.out.println("Enter a value= ");
number = input.nextInt();
double result = 0;
double expectedValue = number;
int k = 0;
while (result < expectedValue) {
k++;
result = sum(k);
}
System.out.println(k
+ " is the term that should be added in order to reach "
+ number + " (" + sum(k) + ")");
}
public static double sum(double k) {
if (k == 1)
return 1 / 3;
else
return ((k / (2 * k + 1)) + sum(k - 1));
}
}

Java program that tells what coins to give out for any amount of change from 1 cent to 99 cents

I have to write a Java program that tells what coins to give out for any amount of change from 1 cent to 99 cents. For example, if the amount is 86 cents, the output would be something like the following:
86 cents can be given as 3 quarters, 1 dime and 1 penny.
Use coin denominations of 25, 10, 5, and 1. Your program will use the following method(among others):
public static int computeCoin(int coinValue,);
// Precondition: 0 < coinValue < 100;
// Postcondition: returned value has been set equal to the maximum
//number of coins of the denomination coinValue cents that can be
//obtained from amount (a different variable) cents. amount has been
//decreased by the value of the coins, that is, decreased by
//returnedValue*coinValue.
So far this is what I have but I think I am missing more can somebody give me a hand?
And I am also not suppose to use doubles instead int.
public class Assignment6{
public static void main(String [] args){
amount = (int)(Double.parseDouble(args[0])*100);
System.out.println("Five: " + computeCoin(500));
System.out.println("one: " + computeCoin(100) );
System.out.println("Q : " + computeCoin(25) );
System.out.println("D : " + computeCoin(10) );
System.out.println("N : " + computeCoin(5) );
System.out.println("P : " + computeCoin(1) );
}
public class Assignment6 {
private static int amount = 0;
public static void main(String[] args) {
amount = (int)(Double.parseDouble(args[0])*100);
System.out.println("Five: " + computeCoin(500));
System.out.println("one: " + computeCoin(100) );
System.out.println("Q : " + computeCoin(25) );
System.out.println("D : " + computeCoin(10) );
System.out.println("N : " + computeCoin(5) );
System.out.println("P : " + computeCoin(1) );
}
public static int computeCoin(int cointValue) {
int val = amount / cointValue;
amount -= val * cointValue;
return val;
}
}
The trick here lies in the computeCoin method, and in the fact that the division is integer division, so val will hold the 'maximum' number of coins of the given value (coinValue) whose total value does not exceed amount.
like this?
public class Assignment6 {
public static int amount;
public static int amountPreserv;
public static void main(String[] args) {
amount = (int) (Double.parseDouble(args[0]) * 100);
amountPreserv = amount;
System.out.println("Five: " + computeCoin(500));
System.out.println("one: " + computeCoin(100));
System.out.println("Q : " + computeCoin(25));
System.out.println("D : " + computeCoin(10));
System.out.println("N : " + computeCoin(5));
System.out.println("P : " + computeCoin(1));
System.out.println("Value inputed : " + amountPreserv);
}
private static int computeCoin(int i) {
int cont = 0;
while (amount > i) {
amount -= i;
cont++;
}
return cont;
}
}
The biggest point to make is that making change is a Greedy Algorithm, meaning that the option that moves you closest to the goal at any given time is the most efficient choice. Therefore, for any amount and any denomination, the most efficient algorithm should be something like this:
int total;
int[] denom = { w, x, y, z };
int[] count = new int[denom.length]
int i = 0;
while (i < denom.length && total > 0) {
while ( total >= denom[i] )
{
total -= denom[i];
count[i]++;
}
i++
}
EDIT: Any denominations is a bit ambitions actually. It's only true of you have a minimum denomination that can guarantee that change can be made every time.

Categories