Calculating the Java Pectorial Sequence

Asked 2 years ago, Updated 2 years ago, 25 views

import java.util.Scanner;

public class Test {

public static void main(String [] args)
{
    double e = 0.0;
    double ins_sum = 0.0;
    int n = 0;
    int ins_fact = 1;
    Scanner sc = new Scanner(System.in);

    System.out.print ("Enter an integer: ");
    n = sc.nextInt();

    for(int i = n; i>=1; i--) {
        for(int j = i; j>=1; j--) {
            ins_fact = ins_fact*j;
        }

        ins_sum = 1.0/ins_fact;
        e += ins_sum;
        ins_fact = 1;
        ins_sum = 0;
    }

    System.out.println ("the value of e is "+e+" when n is "+n+")
}

}

The above code is for calculating "1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! + ..."

Run the code above and type 10 to get the correct answer. But the price I need to find is When n = 200 and n = 10000, if you substitute a number of 34 or more into n, The value of e appears as Infinity...

The result value up to 33 is correct compared to the result calculated by the calculator daily, so the code itself does not seem to be wrong...

Is there a way to solve it??

java

2022-09-21 17:31

1 Answers

Just keep that in mind I should do +1

import java.math.BigDecimal;

public class Test {

    public static void main(String [] args)
    {
        BigDecimal e = new BigDecimal("0.0");
        BigDecimal ins_sum = new BigDecimal("0.0");
        int n = 0;
        //long ins_fact = 1;
        BigDecimal ins_fact = new BigDecimal("1");
        //Scanner sc = new Scanner(System.in);

        //System.out.print ("Enter an integer: ");
        n = 50;//sc.nextInt();

        for(int i = n; i>=1; i--) {
            for(int j = i; j>=1; j--) {
                ins_fact = ins_fact.multiply(BigDecimal.valueOf(j));
            }
            System.out.println(ins_fact);
            ins_sum = BigDecimal.valueOf(1.0/ins_fact.doubleValue());
            e = e.add(ins_sum);
            ins_fact = new BigDecimal("1");
            ins_sum = new BigDecimal("0.0");
        }

        System.out.println ("the value of e is "+e+" when n is "+n+")
    }

}
 When n is 50, the value of e is 1.718281828459045225790675731474643113446000753801893200897038675982544982489290584.


2022-09-21 17:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.