What will be the algorithm for calculating the given series?
Series to be calculated
Here's what I coded till now:
public static double sumOfSeries(double x, int numTerms) { // -1 <= x <= 1
double sum = x;
for(int i = 1; i <= numTerms; i++) {
}
return sum;
}
try to separate the coefficients from polynomials and calculate those in separate methods. Example:
public class NewClass {
public static void main(String[] args) {
int greatestExponent = 9;
double x = 0.5;
System.out.println(calculate(x,greatestExponent));
}
public static double getCoefficient(int n){
double coff = 1;
for(int i=1; i<n; i++){
if(i%2==0){
coff = coff/i; //if even put it in the denominator
}
else{
coff = coff*i; // else numerator
}
}
return coff/n; // at the end divide with the exponent (ex. x^9 /9)
}
public static double calculate(double x, int expo){
double result = 1;
for (int i = 1; i<= expo; i+=2){
result += (getCoefficient(i)*Math.pow(x, i)); //for each odd exponent calculate the cofficient and x^i
}
return result;
}
}
Necessary to find all regularity in proposed equation.
x -> x^3 -> x^5 -> x^7 ->
Then you make separate variable N1=x before loop and N1 *= x*2 at the end of each iteration
1 -> 1 -> 1x3 -> 1x3x5 -> 1x3x5x7 ->
Separate variable N2=1 before lopp and N2 *= (i*2-1) at the end of each iteration
etc, etc
finaly you will combine all this parts together at start of each iteration, like sum += N1*N2*N3/(N4*N5)
Related
I need a Poisson distribution.
Currently I have the following code:
public static int getPoisson(double lambda) {
double l = Math.exp(-lambda);
double p = 1.0;
int k = 0;
do {
k++;
p *= Math.random();
} while (p > l);
return k - 1;
}
I was wondering how I could modify it such that I can generate x number of values all within a defined range i.e., if a = 5, b = 10, and lambda = 6, all values generated will fall within the range of 5 to 10.
Note: I could overload the method, and thus accept range parameters, and call the getPossion method within a loop; discarding anything that doesn't fit this range. However, I would like to check whether there is a mathematically defined means of achieving this and/or whether this approach would be suitable.
EDIT: The means by which I discard 'out of bounds' values:
public static int getPoisson(final double min, final double max, final double lambda) {
int k = 0;
do {
k = getPoisson(lambda);
} while (k < min || k > max);
return k;
}
If you want only get some integers in very small given range with given probability with fixed (or rarely changed) lambda the easiest way is to keep probability tables for each of number and do biased sampling.
Some pseudocode:
public class BoundedSampler {
private final int min;
private final double[] table;
public BoundedSampler(int min, int max, double lambda) {
this.min = min;
this.table = new double[max - min + 1];
double cumulative = 0;
for(int x = min; x <= max; ++x) {
double prob = probability(x, lambda);
table[x - min] = cumulative + prob;
cumulative += prob;
}
for(int i = 0; i < table.length; ++i) {
table[i] /= cumulative;
}
}
public int sample() {
double r = Math.random();
for(int i = 0; i < table.length; ++i) {
if(table[i] <= r) {
return i + min;
}
}
return -1; // impossible: last table value == 1
}
}
Or use alias method to fast value selection.
I am having problems with summing up the products produced from my java loop.
public class ArtificialNeuron {
public ArtificialNeuron(double[] weightings) {
weights = weightings;
inputs = new double[6];
inputs[0] = 1;
}
public void setInput(int index, double newValue) {
inputs[index] = newValue;
}
public int activate(double threshold) {
double x = 0;
for(int i=0; i<inputs.length;i++)
x = inputs[i]*weights[i];
double sum = x+x+x+x+x+x;
if(sum >= threshold) {
return 1;
} else {
return -1;
}
}
}
I ran several Junit test and it always seem to fail on the if else statement. I believe it probably my summation method, but I don't know how I would sum up the products.
Based on your code, I think you wanted to add all of the products together. Instead, you are multiplying the last product by 6 (effectively). It's unclear why you have the temporary x, you can add each product to a default sum of 0. Also, I think a test for sum < threshold is a little easier to read (likewise, always use braces with your loops - it's easier to read and reason about). Like,
public int activate(double threshold) {
double sum = 0;
for (int i = 0; i < inputs.length; i++) {
sum += inputs[i] * weights[i]; // sum = sum + (inputs[i] * weights[i])
}
if (sum < threshold) {
return -1;
}
return 1;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This code is supposed to find the Standard deviation of an random integers in an ArrayList. However, my code for the Standard deviation doesn't show the right outcome. It shows another number then expected.
What am I doing wrong?
import java.io.*;
import java.util.*;
public class Assignment4 {
public static void main(String[] args)
{
ArrayList<Integer> values = new ArrayList<Integer>();
int count = 0;
int total = 0;
Random r = new Random();
for (int i = 1; i <= 10; i++) {
values.add(r.nextInt(90)+ 1);
System.out.println(values);
}
System.out.println(mean(values));
System.out.println(sd(values));
}
public static double mean (ArrayList<Integer> table)
{
int total = 0;
for ( int i= 0;i < table.size(); i++)
{
int currentNum = table.get(i);
total+= currentNum;
}
return total/table.size();
}
public static double sd (ArrayList<Integer> table)
{
double mean= mean(table);
double temp =0;
for ( int i= 0; i <table.size(); i++)
{
temp= Math.pow(i-mean, 2);
}
return Math.sqrt(mean( table));
}
public static void selectionSort(ArrayList<Integer> table)
{
int count = table.size();
for(int pos = 0; pos < count - 1; pos++)
{
int locMin = pos;
for(int i = pos + 1; i < count; i++)
{
if(table.get(i) < table.get(locMin))
locMin = i;
}
int temp = table.get(pos);
table.set(pos, table.get(locMin) );
table.set(locMin, temp);
}
}
}
Your standard deviation calculation has errors:
This is the algorithm for finding the standard deviation:
Step 1: Find the mean.
Step 2: For each data point, find the square of its distance to the mean.
Step 3: Sum the values from Step 2.
Step 4: Divide by the number of data points.
Step 5: Take the square root.
Therefore, your code should look like:
public static double sd (ArrayList<Integer> table)
{
// Step 1:
double mean = mean(table);
double temp = 0;
for (int i = 0; i < table.size(); i++)
{
int val = table.get(i);
// Step 2:
double squrDiffToMean = Math.pow(val - mean, 2);
// Step 3:
temp += squrDiffToMean;
}
// Step 4:
double meanOfDiffs = (double) temp / (double) (table.size());
// Step 5:
return Math.sqrt(meanOfDiffs);
}
Note: Your mean calculation has a loss of precision.
You have:
return total/table.size();
It should be:
return (double) total / (double) table.size();
Here is a sample Standard Deviation Program:
// Beginning of class Deviation
public class Deviation
{
// Beginning of method main
public static void main(String[] args)
{
// Declare and create an array for 10 numbers
double[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Print numbers
printArray(numbers);
// Display mean and deviation
System.out.println("The mean is " + findMean(numbers));
System.out.println("The standard deviation is " +
findDeviation(numbers));
} // End of main
/* Method for computing deviation of double values */
// Beginning of double findDeviation(double[])
public static double findDeviation(double[] nums)
{
double mean = findMean(nums);
double squareSum = 0;
for (int i = 0; i < nums.length; i++)
{
squareSum += Math.pow(nums[i] - mean, 2);
}
return Math.sqrt((squareSum) / (nums.length - 1));
} // End of double findDeviation(double[])
/* Method for computing deviation of int values */
// Beginning of double findDeviation(int[])
public static double findDeviation(int[] nums)
{
double mean = findMean(nums);
double squareSum = 0;
for (int i = 0; i < nums.length; i++)
{
squareSum += Math.pow(nums[i] - mean, 2);
}
return Math.sqrt((squareSum) / (nums.length - 1));
} // End of double findDeviation(int[])
/** Method for computing mean of an array of double values */
// Beginning of double findMean(double[])
public static double findMean(double[] nums)
{
double sum = 0;
for (int i = 0; i < nums.length; i++)
{
sum += nums[i];
}
return sum / nums.length;
} // End of double getMean(double[])
/** Method for computing mean of an array of int values */
// Beginning of double findMean(int[])
public static double findMean(int[] nums)
{
double sum = 0;
for (int i = 0; i < nums.length; i++)
{
sum += nums[i];
}
return sum / nums.length;
} // End of double getMean(int[])
/* Method for printing array */
// Beginning of void printArray(double[])
public static void printArray(double[] nums)
{
for (int i = 0; i < nums.length; i++)
{
System.out.print(nums[i] + " ");
}
System.out.println();
} // End of void printArray(double[])
} // End of class Deviation
Well, I am doing a practice problem (preparing for midterm) and I was able to get one of the outputs correct. However, I am having troublesome getting the average input. It ends up at 12.0 instead of 6.5
Here's the prompt question:5.
Complete the following Java program by filling in the bodies of functions sum(), avg(), and ord(). A call to sum(n) should return the sum of all the integers from 1 to n, while avg(n) returns the average of the same set of numbers. A call to the boolean function ord(x, y, z) returns true if x < y< z and false otherwise. The Function main() should produce the following output
Output:
6.5 true false
This is my code:
class Problem5 {
// sum(): return 1+2+3+..+n
static int sum(int n) { //this is given
int sum = 0;
for(int i=0; i<n; i++) {
sum += n;
}
return n;
}
// avg(): return average of {1,2,..,n}
static double avg(int n) { // given
double sum = 0;
for (int i=1; i<n; i++) {
sum +=n;
}
return sum / n;
}
//ord(): return true if and only if x<y<z
static boolean ord(double x, double y, double z){ //given
if (x < y && y <z){
return true;
} else {
return false;
}
}
public static void main (String[]args) {
System.out.println(avg(12));
System.out.println(ord(1.2,3.4,5.6));
System.out.println(ord(3.4,1.2,5.6));
}
}
Overall I am having trouble coding/ filling in the code for static int sum(int) and static double avg(int).
This:
for (int i=1; i<n; i++){
Will skip n. (it will loop on 1...n-1). For 12, the sum will be 11*12/2, which you then divide by 12, resulting in 11/2 = 6.5
Fix it like so:
for (int i = 1; i <= n; i++) {
(or replace the whole loop by return (double) (n+1) / 2.0)
For your sum function, there is the same error, plus the return value is not good:
return n;
Should be
return sum;
And the increment should be sum += i;, not n (you want 1+2+3+4..., not 12+12+12+12...)
Again, you can replace the whole loop by return n * (n + 1) / 2
I assume your teacher would expect you to learn about re usability, and since your 2 loops in sum and in avg are identical, you could write:
public static double avg(int n) {
return (double) sum(n) / n;
}
A sum is just the addition of all the numbers in a certain range:
static int sum(int n) {
int total = 0;
for(int i = 1; i <= n; i++) {
total += i;
}
return total;
}
Average is just the sum of the range divided by the amount of numbers:
static double avg(int n) {
return sum(n) / (double) n;
}
![enter image description here][1]The question:
Write a function with name ʻ expʼ that ,when given one integer x; returns
with the following approximation. In this function, you should use previous two functions to calculate factorial and power.
This is my code;
import java.util.Scanner;
public class ass7_q3 {
public static int power(int x, int y)
{
int result = 1;
for(int i = 1; i <= y; i++)
{
result = result * x;
}
return result;
}
public static int factorial(int n)
{
int fact = 1;
for(int i = 1; i<= n; i++)
fact = fact * i;
return fact;
}
public static int exp( int x)
{
int result;
result = (power(x,x) / factorial(x) );
return result;
}
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int sum = 0;
int x;
x = read.nextInt();
for(int i=0; i<=10; i++)
{
sum = sum + exp(x);
}
System.out.println(sum);
}
}
However, when I run this code, it always gives me the wrong answer.
What can I do?
You should start by working with doubles instead of integers. You can't expect to approximate a Real number using only integer calculations.
For example, power(x,x) / factorial(x) would always return an integer, since both methods return an int.
5/2 will return 2. You need cast it to double like ((double)5)/2 will return 2.5
You should think about range of integer ( in java 2,147,483,647)
if your input is grater than 12, integer can not handle.
Factorial method will return wrong value. because
factorial(12)=479,001,600 but
factorial(13)=6,227,020,800