Series generation - java

I am trying to find out the sum of the series, 1/2! - 2/3! + 3/4! - 4/5! ... n. Sorry if this sounds awkward but the sum always shows up as 0.0. I can't figure out what's happening and I am just starting out. Can anyone kindly point out the mistake and suggest how to fix it? Thanks!
import java.util.Scanner;
public class Series {
/*
* Series design: 1/2! - 2/3! + 3/4! - 4/5! .. n
*/
static double sum = 0; static int n;
Scanner sc = new Scanner(System.in);
public static int fact(int n){
int fact = 1;
for (int i = 1; i<=n; i++){
fact *= i;
}
return fact;
}
void generate(){
double sign = 1.0; double term;
for (int i = 1; i<=n; i++){
term = i/fact(i+1) * sign;
sum += term;
sign *= -1;
}
}
void accept(){
System.out.println("Enter the value of n:");
n = sc.nextInt();
}
public static void main(String[] args){
Series o = new Series();
o.accept();
o.generate();
System.out.println("The sum of the series is: " +sum);
}
}

i and fact(i+1) are both ints, so you're performing integer division. Since i < fact(i+1), each such term will produce a zero.
You had the right idea with defining sign as a double, but since / and * have the same precedence, you're first performing an integer division and only then multiplying by the double sign. Moving it to the beginning of the expression should do the trick:
void generate(){
double sign = 1.0; double term;
for (int i = 1; i<=n; i++){
term = (sign * i) / fact(i+1);
sum += term;
sign *= -1;
}
}

Your problem is that i/fact(i+1) is an int division, so it is truncated to 0 (since it's smaller than 1).
Change it to (double)i/fact(i+1).
Alternately, you can write
term = sign*i/fact(i+1);
since sign is already double, so it would ensure sign*i would also be double, and the division would be a floating point division.

import java.util.Scanner;
public class Series {
static double sum = 0.0;
static int n=0;
static Scanner sc = new Scanner(System.in);
public static int fact(int n)
{
int fact = 1;
for(int i = 1; i<=n; i++){
fact *= i;
}
return fact;
}
static void generate(){
//because of static property
double sign = 1.0; double term;
for(int i = 1; i<=n; i++){
term = (i* sign)/fact(i+1) ;
sum += term;
sign *= -1;
}
}
static void accept(){
//because of static property
System.out.println("Enter the value of n:");
n = sc.nextInt();
}
public static void main(String[] args){
Series.accept();
Series.generate();
System.out.println("The sum of the series is: " +sum);
}
}

Related

For-loop returning wrong results

I am getting wrong results resolving below task:
Generalized harmonic numbers. Write a program GeneralizedHarmonic.java that takes two integer command-line arguments n and r and uses a for loop to compute the nth generalized harmonic number of order r, which is defined by the following formula:
formula
public class GeneralizedHarmonic {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int i;
double sum = 0;
for (i = 0; i <= a; i++) {
sum += 1 / Math.pow(i, b);
}
System.out.println(sum);
}
}
This is my code but I could not get the correct test output.The output result is always Infinity.
test outputs
You have initliazed int i = 0 in for-loop for (i = 0; i <= a; i++) and so the first element of your harmonic number isn't , but .
The code that works:
public class GeneralizedHarmonic {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
double sum = 0;
for (int i = 1; i <= a; i++) {
sum += 1 / Math.pow(i, b);
}
System.out.println(sum);
}
}

I'm attempting to write a Taylor-expansion calculator in Java, but the program doesn't calculate correctly

I'm trying to create a Java program that will calculate a cosine value with the following equation:
The code to my program is located below. I don't appear to have any errors in my program however no matter what values that I set x and k to, I get the answer Infinity and I cannot figure out what I've done wrong.
The way that the code works, is that the console asks you for a value for x and then a value for k. Then the idea is to have Java compare the result of the equation (the method cosine in the script) with the Math.cos() function.
The method cosine is split up into two parts, cosinenumerator and cosinedenominator which is then divided with each other to become cosineresult at the end.
The loop for cosinedenominator is supposed to emulate a "factorial" in the equation.
Any help would be greatly appreciated.
import java.util.Scanner;
public class Cosine {
public static void main(String[] args) {
Scanner consolecosine = new Scanner(System.in);
System.out.println("Enter x value:");
double x = consolecosine.nextDouble();
System.out.println("Enter k value:");
int k = consolecosine.nextInt();
double cosineresult = cosine(x, k);
System.out.println("Using the Math.cos function yields: " + Math.cos(90));
System.out.println("Using the Taylor expansion equation yields: " + cosineresult);
}
public static double cosine(double x, int k) {
double cosineresult = 0;
double cosinenumerator = 0;
double cosinedenominator =0;
int i = 0;
int j = 0;
for(i = 0; i <= k; i++) {
cosinenumerator += Math.pow((-1),i) * Math.pow(x, (2*i));
}
for(j = 0; j <= (2*i); j++) {
cosinedenominator *= (2*j);
}
cosineresult = cosinenumerator / cosinedenominator;
return cosineresult;
}
}
Here's a working version (note that x is in radians; not degrees):
cosine(Math.PI, 15) yields -1.0000000000000002, which is about right.
public static double cosine(double x, int k) {
double cosineresult = 0;
double cosinedenominator = 1; // initial value 0! = 1; overflows at k = 86
int j = 2; // next multiplier in denominator factorial (skip 1)
for (int i = 0; i <= k; i++) {
double cosinenumerator = Math.pow((-1),i) * Math.pow(x, (2 * i));
// Continue calculation of factorial from last value
while (j <= 2 * i) {
cosinedenominator *= j++;
}
cosineresult += cosinenumerator / cosinedenominator;
}
return cosineresult;
}

Java average method stuck

So guys this is my code. the code runs fine but I don't get the proper average. Could someone please fix it.
import java.util.Scanner;
public class test {
public static double Avg(int amt, int num) {
int tot = 0;
tot = tot + num;
int average = tot/amt;
return average;
public static void main(String[] args) {
double average_ICT_01 = 0;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> ICT_01 = new ArrayList<Integer>();
for (int i=0; i<3; i++) {
int num = sc.nextInt();
ICT_01.add(num);
}
int length01 = ICT_01.size();
for (int c=0; c<3; c++) {
int num1 = ICT_01.get(c);
average_ICT_01 = Avg(length01,num1);
}
System.out.println(average_ICT_01);
}
}
The arithmetic average of n numbers is their sum divided by n. So a method for calculating the average of all the numbers in a vector should be:
public static double avg(List<int> vec){
//Sum all numbers
long sum = 0;
for(int i=0;i<vec.size();i++){
sum = sum + vec.get(i);
}
//Divide by the number of numbers
double avg = sum/vec.size();
//Return the average
return avg;
}

How to compute sum series 1+1/2...+1/n

I'm having trouble trying to find the sum of this series non-recursively
So far I have:
public static double sum_nr(int n) {
int result = 0;
for (int i = 1; i<=n; i++)
{
result=result+1/(i+1);
}
return result;
}
public static void main(String[] args){
int n= 4;
System.out.println("Calculation for sum_nr(n) " + n + " is "+ sum_nr(n));
}
I keep getting 0.0 as the sum.
What am I doing wrong?
I think it's due to not using the right type. You're doing integer division rather than using a float type.
public static double sum_nr(int n) {
double result = 0;
for (double i = 0; i < n; i++)
{
result=result+1.0/(i+1);
}
return result;
}
Integer division will lead to 0 results. you should use float/double instead of int for variable result.
result=result+1/(i+1); will always give 0 as i is an integer. Assign i value to a float and use that
float result = 0f; // declare result as float too or double for (int
i = 1; i<=n; i++)
{ float val = i;
result=result+1/(float+1);
}
Same as everyone else says but their answers aren't complete.
public static double sum_nr(int n) {
float result = 0;
for (int i = 1; i<=n; i++){
result=result+1/((float)i+1);
}
return result;
}
result needs to be a float, or double, but you also need to cast i as a float, or double, as well. No need to create a new variable
The series you are referring to is the harmonic series. There's a closed form approximation for this.
H(n) = ln(n) + gamma + 1/(2n) - 1/(12n^2)
where gamma is the Euler-Mascheroni constant. See here.
In Java, here's some code to both compute correctly and show the difference of the approximation to the actual as n grows. It will become asymptotically smaller:
constant double EULER_MASCHERONI = 0.57721566490153286060651209008240243104215933593992;
public static double approximateHarmonicSummation(int n) {
return Math.log(n) + EULER_MASCHERONI + 0.5 * n - 1.0 / (12.0 * Math.pow(n, 2));
}
public static double sum_nr(int n) {
double result = 0;
for (double i = 0; i < n; i++) {
result += 1.0 / (i + 1);
}
return result;
}
public static void main(String[] args) {
double approx = 0.0;
double actual = 0.0;
for (int n = 0; n < 1000; n++) {
approx = approximateHarmonicSummation(n);
actual = sum_nr(n);
System.out.println("Calculation for approximation of sum_nr(n) " + n + " is "+ approx);
System.out.println("Calculation of sum_nr(n) " + n + " is "+ actual);
System.out.printlin("Difference = " + (actual - approx) + "\n");
}
}
Hopefully that helps.

Find factorial of large numbers in Java

I tried to find the factorial of a large number e.g. 8785856 in a typical way using for-loop and double data type.
But it is displaying infinity as the result, may be because it is exceeding its limit.
So please guide me the way to find the factorial of a very large number.
My code:
class abc
{
public static void main (String[]args)
{
double fact=1;
for(int i=1;i<=8785856;i++)
{
fact=fact*i;
}
System.out.println(fact);
}
}
Output:-
Infinity
I am new to Java but have learned some concepts of IO-handling and all.
public static void main(String[] args) {
BigInteger fact = BigInteger.valueOf(1);
for (int i = 1; i <= 8785856; i++)
fact = fact.multiply(BigInteger.valueOf(i));
System.out.println(fact);
}
You might want to reconsider calculating this huge value. Wolfram Alpha's Approximation suggests it will most certainly not fit in your main memory to be displayed.
This code should work fine :-
public class BigMath {
public static String factorial(int n) {
return factorial(n, 300);
}
private static String factorial(int n, int maxSize) {
int res[] = new int[maxSize];
res[0] = 1; // Initialize result
int res_size = 1;
// Apply simple factorial formula n! = 1 * 2 * 3 * 4... * n
for (int x = 2; x <= n; x++) {
res_size = multiply(x, res, res_size);
}
StringBuffer buff = new StringBuffer();
for (int i = res_size - 1; i >= 0; i--) {
buff.append(res[i]);
}
return buff.toString();
}
/**
* This function multiplies x with the number represented by res[]. res_size
* is size of res[] or number of digits in the number represented by res[].
* This function uses simple school mathematics for multiplication.
*
* This function may value of res_size and returns the new value of res_size.
*/
private static int multiply(int x, int res[], int res_size) {
int carry = 0; // Initialize carry.
// One by one multiply n with individual digits of res[].
for (int i = 0; i < res_size; i++) {
int prod = res[i] * x + carry;
res[i] = prod % 10; // Store last digit of 'prod' in res[]
carry = prod / 10; // Put rest in carry
}
// Put carry in res and increase result size.
while (carry != 0) {
res[res_size] = carry % 10;
carry = carry / 10;
res_size++;
}
return res_size;
}
/** Driver method. */
public static void main(String[] args) {
int n = 100;
System.out.printf("Factorial %d = %s%n", n, factorial(n));
}
}
Hint: Use the BigInteger class, and be prepared to give the JVM a lot of memory. The value of 8785856! is a really big number.
Use the class BigInteger. ( I am not sure if that will even work for such huge integers )
Infinity is a special reserved value in the Double class used when you have exceed the maximum number the a double can hold.
If you want your code to work, use the BigDecimal class, but given the input number, don't expect your program to finish execution any time soon.
The above solutions for your problem (8785856!) using BigInteger would take literally hours of CPU time if not days. Do you need the exact result or would an approximation suffice?
There is a mathematical approach called "Sterling's Approximation
" which can be computed simply and fast, and the following is Gosper's improvement:
import java.util.*;
import java.math.*;
class main
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int i;
int n=sc.nextInt();
BigInteger fact = BigInteger.valueOf(1);
for ( i = 1; i <= n; i++)
{
fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println(fact);
}
}
Try this:
import java.math.BigInteger;
public class LargeFactorial
{
public static void main(String[] args)
{
int n = 50;
}
public static BigInteger factorial(int n)
{
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++)
result = result.multiply(new BigInteger(i + ""));
return result;
}
}
Scanner r = new Scanner(System.in);
System.out.print("Input Number : ");
int num = r.nextInt();
int ans = 1;
if (num <= 0) {
ans = 0;
}
while (num > 0) {
System.out.println(num + " x ");
ans *= num--;
}
System.out.println("\b\b=" + ans);
public static void main (String[] args) throws java.lang.Exception
{
BigInteger fact= BigInteger.ONE;
int factorialNo = 8785856 ;
for (int i = 2; i <= factorialNo; i++) {
fact = fact.multiply(new BigInteger(String.valueOf(i)));
}
System.out.println("Factorial of the given number is = " + fact);
}
import java.util.Scanner;
public class factorial {
public static void main(String[] args) {
System.out.println("Enter the number : ");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
factorial f=new factorial();
int result=f.fact(n);
System.out.println("factorial of "+n+" is "+result);
}
int fact(int a)
{
if(a==1)
return 1;
else
return a*fact(a-1);
}
}

Categories

Resources