Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic trigonometry in Java

I've been struggling around with this problem for a couple of days, so after alot of googling I decided to ask here instead.

Anyway, I need to use the Math.tan() method, but it doesn't work really as I want. Becase if I set up an double variable: double i = opposite/adjacent and then use the Math.tan() method on that, it just returns 0.0! For example:

double i = 480/640;
System.out.println(Math.tan(i));

But it still returns zero! I read that the Math.tan() method only returns the "Radian" value. But because of that it should'nt return zero? Or am I wrong? I know that if i use a real calculator and do tan(480/640) it will return what I want.

So I hope someone understands me and wants to help me! Thanks in advance! (Btw I'm sorry for bad english)

like image 515
GuiceU Avatar asked Dec 27 '22 09:12

GuiceU


2 Answers

In int calculations, 480/640 is 0. So the result of i will be 0.0.

You need to write double i = 480.0/640; (At least one of the numbers has to be written as a double).

You can also write: double a = 480, b = 640; and then if you write double i = a/b; you'll get good result.

like image 166
Maroun Avatar answered Jan 14 '23 21:01

Maroun


When you do maths without casts Java will implicitly make literals integers first - in your case this will indeed result in 0.

Cast the values before doing your maths and it'll be fine:

    double i = 480D/640D;
    System.out.println(i);

or

    double i = (double)480/(double)640;
    System.out.println(i);

or

    double numerator = 480;
    double denominator = 640;
    double i = numerator / denominator;
    System.out.println(i);
like image 34
Sean Landsman Avatar answered Jan 14 '23 23:01

Sean Landsman