大输入的 java.lang.StackOverflowError 异常 [英] java.lang.StackOverflowError exception for large inputs
问题描述
基本上,我正在编写一个程序来手动进行简单的除法,我希望小数位最多为 10^6 位.该程序适用于输入 <3000,但当我走高时,它显示:线程main"中的异常java.lang.StackOverflowError
Basically, I'm writing a program to do a simple division manually where I want the decimal place upto 10^6 places. The program works for inputs <3000, but when I go higher, it shows:
Exception in thread "main" java.lang.StackOverflowError
这是我的代码:
{
....
....
int N=100000;//nth place after decimal point
String res=obj.compute(N,103993.0,33102.0,ans); //division of 103993.0 by 33102.0
System.out.println(res);
}
public String compute (int n, double a, double b, String ans){
int x1=(int)a/(int)b;
double x2=a-x1*b;
double x3=x2*10;
int c=0;
if (n==0||n<0)
return ("3."+ans.substring(1));
else if (x3>b){
ans+=""+x1;
c=1;
}
else if(x3*10>b){
ans+=x1+"0";
c=10;
}
else if(x3*100>b){
ans+=x1+"00";
c=100;
}
else if(x3*1000>b){
ans+=x1+"000";
c=1000;
}
else if(x3*10000>b){
ans+=x1+"0000";
c=10000;
}
return compute(n-String.valueOf(c).length(),x3*c,b,ans);
}
我不是 Java 的核心程序员.我需要帮助来解决这种情况.我阅读了一些关于增加堆栈大小的 SO 帖子,但我不理解该方法.
I'm not any hard-core programmer of Java. I need help in tackling this situation. I read some SO posts about increasing the stack size, but I didn't understand the method.
推荐答案
从compute() 到compute 的递归调用导致堆栈溢出.改变你的方法来使用循环而不是递归,它会更好地扩展.请参阅维基百科页面,了解您可以使用的不同划分算法:https://en.wikipedia.org/wiki/Division_%28digital%29
The recursive call from compute() to compute is causing the stack to overflow. Alter your method to use a loop rather than recursion and it would scale much better. See the wikipedia page for different division algorithms you could use: https://en.wikipedia.org/wiki/Division_%28digital%29
或者像这样使用 BigDecimal:
public class Main {
public static void main(String... args) {
final int precision = 20;
MathContext mc = new MathContext(precision, RoundingMode.HALF_UP);
BigDecimal bd = new BigDecimal("103993.0");
BigDecimal d = new BigDecimal("33102.0");
BigDecimal r = bd.divide(d, mc);
System.out.println(r.toString());
}
}
输出:3.1415926530119026041
Output:3.1415926530119026041
设置精度以获得所需的小数位数.
Set precision to get the number of decimal places you want.
这篇关于大输入的 java.lang.StackOverflowError 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!