【问题标题】:Computing sine and cosine计算正弦和余弦
【发布时间】:2016-06-16 22:08:49
【问题描述】:
import java.util.*;
import java.math.*;
public class SinCos{
    public static void main(String args[]){
        Scanner kb=new Scanner(System.in);
        System.out.println("Enter the angle for cosine: ");
        double anglecos=kb.nextDouble();
        System.out.println("Enter the number of expansions required:");
        int n=kb.nextInt();
        System.out.println("Enter the angle for sine:");
        double anglesin=kb.nextDouble();
        System.out.println("Enter the number of expansions required:");
        int n2=kb.nextInt();
        System.out.println("Cosine: "+workCos(anglecos,n));
        System.out.println("Sine: " +workSin(anglesin,n2));

    }

    public static double workCos(double angle, int num){
        double ans=0;
        int times;
        for(int k=0;k<=num;k++){
            times=(2*k);

            ans=(ans + ((Math.pow(-1,k)*Math.pow(angle,times))/(fact(times))));

        }
        return ans;
    }

    public static double workSin(double angle, int num){
        double ans=(angle*Math.PI)/180;
        int times;
        for(int k=0;k<=num;k++){
            times=(2*k)+1;

            ans=(ans + ((Math.pow(-1,k)*Math.pow(angle,times))/(fact(times))));
            System.out.println(ans);
        }
        return ans;
    }

    public static int fact(int num){

        if(num==0||num==1){
            return 1;
        }
        else{
            return num* fact(num-1);
        } 

    }
}

在上面的这段代码中,我试图计算正弦和余弦。不过我是 没有得到正确的结果。这似乎完全合乎逻辑。为此,我 使用泰勒级数。你能告诉我我的问题是什么吗 代码?

【问题讨论】:

  • 而输入的参数值是?
  • “我没有得到正确的结果”是非常不具体的。请尝试调试代码。
  • 输入是角度和系列展开的次数
  • 例如 cos(90) 不给我答案 0 它给了 -7.0985
  • 如果 n 大于 15 我得到答案 NaN

标签: java runtime-error nan


【解决方案1】:

遗憾的是,13! 及更高版本会溢出 Java 中的 int 类型。

因此,fact(int num) 中任何大于 12 的 num 值都会产生意想不到的结果。

一种补救方法是使用long,它可以让您达到19!,此时系列应该已经充分收敛。使用double 将产生更多项,任何精度损失都在您的系列方法的精度范围内。

【讨论】:

    【解决方案2】:

    我认为你的公式有点不对劲。 Take a look here.

    试试这样的罪:​​p>

    public static double workSin(double angle, int num){
        double ans = 0;
        for(int n = 1; n <= num; n++) {
            ans += Math.pow(-1, n - 1) * Math.pow(angle, 2*n - 1) / fact(2*n - 1);
            System.out.println(ans);
        }
        return ans;
    }
    

    和cos这样的:

    public static double workCos(double angle, int num) {
        double ans = 1;
        for(int n = 1; n < num; n++) {
            ans += Math.pow(-1, n) * Math.pow(angle, 2*n) / fact(2*n);
            System.out.println(ans);
        }
        return ans;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      相关资源
      最近更新 更多