如何在Java中对Sin和Cos进行平方?

时间:2016-06-25 04:18:30

标签: java math

我需要这个java练习的帮助。说明是

  

编写一个使用Math.sin()和Math.cos()来检查的程序   对于任何输入的θ,sin 2 θ+ cos 2 θ的值约为1   命令行参数。只需打印该值即可。为什么价值观没有   总是正好1?

到目前为止我的代码(这是我的第一个代码,所以请不要苛刻判断)。

 public class math {
     public static void main(String[] args) {

         //Changes the data types from string to double
         double a = Double.parseDouble(args[0]);
         double b = Double.parseDouble(args[1]);

         //Does the calculation math functions
         double s = 2*Math.sin(a);
         double c = 2*Math.cos(b);
         double target = .9998; // var for comparing if less than 1
         double answer = s + c;

         // Prints the answer and checks whether its less than 1
         System.out.println(answer < target);
         System.out.println(answer);
     }   
 }
我猜想要平衡罪和cos。如果有人有关于如何摆正罪和费用的快速建议,如果我的小程序中有错误,我将非常感谢你的帮助。

3 个答案:

答案 0 :(得分:1)

我认为你要做的就是这个。你有这个错误的意思“罪^2θ”。它的实际意义是sin 2 θ。同样的cos。这是您要查找的代码。

double a = Double.parseDouble(args[0]);

//Does the calculation math functions
double s = Math.pow(Math.sin(a),2);
double c = Math.pow(Math.cos(b),2);
double target = .9998; // var for comparing if less than 1
double answer = s + c;

// Prints the answer and checks whether its less than 1
System.out.println(answer < target);
System.out.println(answer);

答案 1 :(得分:1)

你有一个theta:你需要args [0]而不是args [1] 所以示例代码中为a=b

平衡罪和cos并添加:

选项1:

double stheta = Math.sin(theta);
double ctheta = Math.cos(theta);
double answer = stheta*stheta + ctheta*ctheta;

选项2:

double s2 = Math.pow(Math.sin(theta),2);
double c2 = Math.pow(Math.cos(theta),2);
double answer = s2 + c2;  

工作示例代码:

package javaapplication1;

public class JavaApplication1 {

    public static void main(String[] args) {
        double theta = Double.parseDouble(args[0]);
        double stheta = Math.sin(theta);
        double ctheta = Math.cos(theta);
        double answer = stheta*stheta + ctheta*ctheta;
        System.out.println(answer);
    }   
}

并看到:
Java - does double and float percision depend on the machine?
Test Number For Maximum Precision In Java

答案 2 :(得分:1)

浮点数不是精确的表示。双精度64位IEEE浮点表示仅提供17-18位数字,因此您始终将差异与容差进行比较。

我建议将数字乘以一个数字,以便使用Math.pow()进行平方。

这是一个JUnit测试,显示我是如何做到的:

package math;

import org.junit.Test;
import org.junit.Assert;

/**
 * Created by Michael
 * Creation date 6/25/2016.
 * @link https://stackoverflow.com/questions/38024899/how-do-i-square-sin-and-cos-in-java
 */
public class MathTest {

    public static final double TOLERANCE = 1.0e-8;

    @Test
    public void testUnitCircleIdentity() {
        int n = 10;
        double t = 0.0;
        for (int i = 0; i < n; ++i) {
            double s = Math.sin(t);
            double c = Math.cos(t);
            double actual = s*s + c*c;
            Assert.assertEquals(1.0, actual, TOLERANCE);
            t += Math.PI/n;
        }
    }
}