Programming a series - java

I'm having trouble with my exercise.
I'm supposed to write a program, which calculates this series and and which gives out the value every loop. The series also needs to break if the change of the series value is lower than 10^-5 in a loop.
I hope my explanation was understandable so far.
This is what I came up with:
public static void main(String [] args) {
double sum = 0;
double summand;
double k = 1;
do
{
summand = 1.0/Math.pow(k, 2);
sum = 6 * (sum + summand);
k++;
}
while (summand > 1E-5);
System.out.println(sum);
}
Now I need help, since I'm very new to Java and I have no clue whether this is right or wrong.
Thanks for your help in advance!

Your sum line is wrong - as written you're cumulatively multiplying your value so far in every iteration, whereas you should be able to see from the original question posed that the factor of six only applies once.
You need:
sum = sum + 6 * summand
or alternatively leave the multiplication by 6 until after the summation, which more closely matches the given formula:
do {
summand = 1.0 / (k * k);
sum += summand;
} while (summand > 1e-5);
sum *= 6.0;

Just move the System.out.println(sum) inside the loop.
public static void main(String [] args) {
double sum = 0;
double summand;
double k = 1;
do
{
summand = 1.0/Math.pow(k, 2);
sum = 6 * (sum + summand);
k++;
System.out.println(sum); // <-- here it's right
}
while (summand > 1E-5);
}
That way it will be printed for every iteration of the loop.

Related

Optimisation in Java Using Apache Commons Math

I'm trying to minimise a value in Java usingcommons-math. I've had a look at their documentation but I don't really get how to implement it.
Basically, in my code below, I have a Double which has the expected goals in a soccer match and I'd like to optimise the probability value of under 3 goals occurring in a game to 0.5.
import org.apache.commons.math3.distribution.PoissonDistribution;
public class Solver {
public static void main(String[] args) {
final Double expectedGoals = 2.9d;
final PoissonDistribution poissonGoals = new PoissonDistribution(expectedGoals);
Double probabilityUnderThreeGoals = 0d;
for (int score = 0; score < 15; score++) {
final Double probability =
poissonGoals.probability(score);
if (score < 3) {
probabilityUnderThreeGoals = probabilityUnderThreeGoals + probability;
}
}
System.out.println(probabilityUnderThreeGoals); //prints 0.44596319855718064, I want to optimise this to 0.5
}
}
The cumulative probability (<= x) of a Poisson random variable can be calculated by:
In your case, x is 2 and you want to find lambda (the mean) such that this is 0.5. You can type this into WolframAlpha and have it solve it for you. So rather than an optimisation problem, this is just a root-finding problem (though one could argue that optimisation problems are just finding roots.)
You can also do this with Apache Commons Maths, with one of the root finders.
int maximumGoals = 2;
double expectedProbability = 0.5;
UnivariateFunction f = x -> {
double sum = 0;
for (int i = 0; i <= maximumGoals; i++) {
sum += Math.pow(x, i) / CombinatoricsUtils.factorialDouble(i);
}
return sum * Math.exp(-x) - expectedProbability;
};
// the four parameters that "solve" takes are:
// the number of iterations, the function to solve, min and max of the root
// I've put some somewhat sensible values as an example. Feel free to change them
double answer = new BisectionSolver().solve(Integer.MAX_VALUE, f, 0, maximumGoals / expectedProbability);
System.out.println("Solved: " + answer);
System.out.println("Cumulative Probability: " + new PoissonDistribution(answer).cumulativeProbability(maximumGoals));
This prints:
Solved: 2.674060344696045
Cumulative Probability: 0.4999999923623868

I'm trying to convert a binary number to a decimal number but my Output is always 0

Here is my code. I tried to Convert the binary to a Char array, then multiply each char in the array by 2 to the power of its corresponding number in the array, then sum up all the values of the char array into a double. New to programming so a bit confused. My input Binary is txfBinaryInput, and my output label is lblDisplay.
private void btnProcessActionPerformed(java.awt.event.ActionEvent evt)
{
if (txfBinaryInput.getText().equals(""))
{
lblDisplay.setText("ERROR: NO INPUT");
} else
{
int n = 0;
int[] binaryValueStorage = new int[100];
double[] decimalValueStorage = new double[100];
String binaryInput = txfBinaryInput.getText();
int binaryNumber = binaryInput.length();
char[] binaryDigits = binaryInput.toCharArray();
for (int i = 0; i >= binaryNumber; i++)
{
binaryValueStorage[n] = binaryDigits[n];
decimalValueStorage[n] = binaryValueStorage[n] * (Math.pow(2, n));
n++;
}
double sum = 0;
for (double a : decimalValueStorage)
{
sum += a;
}
lblDisplay.setText("The Deciaml Value Is " + sum);
}
}
Beware: in your for loop condition, you have i >= binaryNumber instead of i < binaryNumber, therefore your program will never enter the loop!
And on a side note, why are you using two variables, i and n, for the same purpose (incrementing and accessing the array)?
Edit: another issue:
In binary numbers, lower order bits are to the right, but in arrays, indices are from left to right!!
So you want your rightmost digit to be multiplied by 2^0, the next one right to its left by 2^1, and so on.
But in your code, what is happening is the opposite: it is the leftmost digit (your digit at index 0) that is being multiplied by 2^0!
To fix, you can either:
1) reverse your binaryDigits array before starting to convert, and keep the rest of your code untouched
2) replace decimalValueStorage[n] = binaryValueStorage[n] * (Math.pow(2, n)); by decimalValueStorage[n] = binaryValueStorage[n] * (Math.pow(2, binaryNumber - n));
Hope this helps!
Well, this is a lot to throw at you, but this is how I'd attack this problem:
public class BinaryToDecimalTest {
private static long binaryToDecimal(String binaryInput)
{
long sum = 0;
for (int i = 0 ; i < binaryInput.length() ; i++) {
sum *= 2;
if (binaryInput.charAt(i) == '1')
sum += 1;
}
return sum;
}
private static void test(String binaryInput) {
long n = binaryToDecimal(binaryInput);
System.out.println(String.format("The Deciaml Value of %s Is %d", binaryInput, n));
}
public static void main(String...args) {
test("0100");
test("1011");
test("1011");
test("10000000");
test("10000000000000000");
}
}
Result:
The Deciaml Value of 0100 Is 4
The Deciaml Value of 1011 Is 11
The Deciaml Value of 1010 Is 10
The Deciaml Value of 10000000 Is 128
The Deciaml Value of 10000000000000000 Is 65536
I don't want to just hit you with code, but I didn't know where to start given all of the issues with your code. I wanted you to see how directly you can often attack a problem. I'd be happy to keep working with you, and explain what's going on here.
The one dirty trick I'm using is multiplying the entire accumulated sum by two each time around. This lets you work naturally from the front of the array, rather than having to work your way backwards. The first digit gets multiplied by 2 (length - 1) times, the second (length - 2) times, etc., down to the last number, which doesn't get multiplied at all.

Trying to Solve Project's Euler's First Questions Using Java, Am Having Trouble Returning the Result

I am trying to make a program that solves Project Euler's First Problem. However I am having trouble returning my sum.
To approach this problem, I am trying to first add up all of the multiples of three and assigning that value of the added multiples to the integer sum. Then I am trying to do the same with the multiples of five accordingly.
Finally I am trying to add the two sums together, the sum of the three multiples and the sum of the five multiples, and them printing out the coalesced value of the two sums via the last sum.
This is the Java code I am trying to use to achieve this.
public class Main {
public static void main(String[] args) {
int sum = 0;
int t = 3;
while (sum < 1000) {
if (sum % 3 == 0)
sum += t;
}
int sum2 = 0;
int f = 5;
while (sum2 < 1000) {
if (sum % 5 == 0)
sum += f;
}
int sum3 = sum + sum2;
System.out.println(sum3);
}
}
I did get one error saying sum2 < 1000 is always true. However, I do not understand how to fix this problem.
Any help is utterly appreciated.
check the comments, hope it helped.
public static void main(String []args){
int sum = 0; //store all the numbers
int t = 3; // the starting point (it can be 3 if you want)
while (t < 1000) { // as long t is lower than 1000
if ( t % 3 == 0 || t % 5 == 0) { //check if t is divided by 3 or 5
sum += t; //add to sum
}
t++; //add 1 to t (t will increase and eventualy be bigger than 1000)
}
System.out.println(sum); //print sum
}

Clarification on "Calculate e^x without inbuilt functions in Java"

The question was basically to calculate e^x without inbuilt functions in Java.
The sequence to code was e^x = 1+x+x2/2!+x3/3!+x4/4!+ ...
Here was my attempt at the question:
public static void myexp(double x, double i){
double j = 1.0;
double sum = x;
while (j <= i){
j = j + 1;
sum = sum + (sum * (x / (j)));
System.out.println(sum + 1 + x);
}
}
public static void main(String[] args) {
double x = 1;
double i = 5.0;
myexp(x, i);
}
Now it wasn't working, and eventually I gave in and looked up what a model answer should look like (I know, I know). Here is what it is (in the style of my code):
public static void myexp(double x, double i){
double j = 1.0;
double sum = x;
double result = 1.0;
while (j <= i){
j = j + 1;
sum = sum * (x / (j));
result = result + sum;
System.out.println(result + x);
}
}
Now the difference is the inclusion of the 'results' variable, which delineates the summation of the sequence. However, I thought I had incorporated that when I wrote
"sum = sum+(sum*(x/(j)));".
But the machine recognises one style and not the other. What gives?
In each iteration you are supposed to add to the total sum the term
sum * x / j
where sum is the term added in the previous iteration.
This means you must store the term added in the previous iteration in a separate variable.
If you use the same variable for the total result (which is supposed to be the sum of all the terms of all iterations) and for the term of the current iteration (sum), you get an entirely different result.
In other words
sum = sum + (sum * (x / (j)));
is not equivalent to
sum = sum * (x / (j));
result = result + sum;
since the value of sum depends on the previous value of sum, and therefore you can't eliminate that variable.

can someone explain the steps to compute this equation? Java

Write a program that computes the following equation.
100/1+99/2+98/3+97/4+96/5...3/98+2/99+1/100
I am not asking for a solution. Yes this is a homework problem, but I am not here to copy paste the answers. I asked my professor to explain the problem or how should I approach this problem? She said "I can't tell you anything."
public static void main(String[] args){
int i;
for(i = 100; i >= 1; i--)
{
int result = i/j;
j = j+1;
System.out.println(result);
}
}
You can try to observe a "trend" or "pattern" when solving questions of this type.
Given: 100/1+99/2+98/3+97/4+96/5...3/98+2/99+1/100
We derived: Numerator/Denominator, let's call it n divide by d (n/d)
Pattern Observed:
n - 1 after every loop
d + 1 after every loop
So, if you have 100 numbers, you need to loop 100 times. Thus using a for-loop which loops 100 times will seemed appropriate:
for(int n=0; n<100; n++) //A loop which loops 100 times from 0 - 100
To let n start with 100, we change the loop a little to let n start from 100 instead of 0:
for(int n=100; n>0; n--) //A loop which loops 100 times from 100 - 0
You settled n, now d needs to start from 1.
int d = 1; //declare outside the loop
Putting everything together, you get:
int d = 1;
double result = 0.0;
for (int n=100; n>0; x--)
{
result += (double)n/d; //Cast either n or d to double, to prevent loss of precision
d ++; //add 1 to d after every loop
}
You are on the right track. You need to loop like you've done, but then you need to SUM up all the results. In your example you can try:
result = result + i/j;
or
result += i/j;
Note that the declaration of result needs to be outside the loop otherwise you are always initializing it.
Also think about the division (hint), you are dividing integers...
What you have is a series.
There is more than one way to define a series, but all things being the same it's more intuitive to have the index of a series increase rather than decrease.
In this case, you could use i from 0 to 99.
Which in java can be:
double sum = 0;
for (int i = 0; i < 100; i++) {
sum += (100 - i) / (double) (1 + i);
}
if you want the result in the same format then do :
int j = 100;
double sum=0;
for (int i = 1; i <= 100; i++) {
sum += ((double) j / i); // typecast as least one of i or j to double.
System.out.print(j + "/" + i+"+");
j--;
}
// here print the sum

Categories