Help with the correct parameters to Math.tan - java

import java.util.Scanner;
public class a {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("enter #");
long a = in.nextLong();
long b = (long) Math.toRadians(a);
long c = (long) Math.tan(b);
System.out.println(c);
}
}
Above is my attempt to make Math.tan spit out the correct values of an angle in degrees. I know the method math.tan accepts only angles in radians as a parameter. I can't get correct value for angles of 90, 270... Using a double doesn't yield correct answers.

You will need to use doubles for b and c.
However, note that tan of 90 and 270 degrees is undefined, for example see the graph here:
http://www.intmath.com/Trigonometric-graphs/4_Graphs-tangent-cotangent-secant-cosecant.php

Of course you cannot get a nice value for 90 degrees, because tan is not defined for that angle. This is clear from the definition
tan(x) = sin(x) / cos(x).
If x = 90°, then cos(x) = 0, so you get a division by zero. The same thing applies to 270°, and in fact all odd multiples of 90°. (Now, computers are numerical beasts, and pi/2 radians cannot be represented exactly (in any base), in addition to cos being computed numerically, so instead of NaN or INF you will likely get a huge number, because the denominator is very close to zero, but not necessarily equal to zero, because of numerical approximation.)
Also, long is an integer type. Integer precision might be good enought for your needs when it comes to angles expressed in degrees (0, 1, 2, ..., 358, 359). But in radians, one full lap around a circle corresponds to the angles 0 radians to 2π, where 2π ~ 6.28. Hence b cannot be an integer, and neither can c.

This works just fine:
public class TanDemo
{
public static void main(String[] args)
{
for (int degrees = -89; degrees < 90; ++degrees)
{
double radians = Math.toRadians(degrees);
System.out.println("deg: " + degrees + " rad: " + radians + " tan: " + Math.tan(radians));
}
}
}

Use double as a starting point for the input and output of methods like Math.toRadians(double)=>double and Math.tan(double)=>double:
import java.util.Scanner;
public class a {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("enter #");
double a = in.nextDouble();
double b = Math.toRadians(a);
double c = Math.tan(b);
System.out.println(c);
}
}
On a domain note – as Saxon Druce pointed out – the tangent of n*90° (n*π/2 rads) is undefined. Correct answers at exactly n*π/2 for n is an odd whole number are not possible. More specifically tan(x) approaches ∞ as x increases towards n*π/2. It is also true that tan(X) approaches -∞ as x decreases towards n*π/2.

Related

Running into errors while executing circle program in java

I am having trouble inputting the radius of a circle and angle of a circle (deg) while receiving the output with the values given plus the angle in radians, arc length and polar area all as floats. Here is what I have.
import java.util.Scanner;
public class MyCircles {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("1st: Please enter a radius (integer) :");
int radius01 = input.nextInt();
System.out.println("1st: Please enter angle (in degrees between 0 and 360) :");
int angledeg01 = input.nextInt();
input.close();
System.out.printf("%s%14s%15s%19s%24s\n", "Radius (inch)", "Angle (deg)", "Angle (rad)", "ArcLength (inch)", "Polar Area (sq. inch)");
System.out.printf("%13d%14d", radius01, angledeg01);
float anglerad01 = radius01 * (Math.PI / 180.0f);
Trying to achieve this:
Radius(inch) Angle(deg) Angle(rad) ArcLength(inch) Polar Area(sq.inch)
3 31 0.54 1.62 2.43
All in columns but I keep running into cannot convert into float error. Also cannot use the MathtoRadians functions. Must use hard code to show work. Suggestions?
anglerad01 should be double instead of float
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("1st: Please enter a radius (integer) :");
int radius01 = input.nextInt();
System.out.println("1st: Please enter angle (in degrees between 0 and 360) :");
int angledeg01 = input.nextInt();
input.close();
System.out.printf("%s%14s%15s%19s%24s\n", "Radius (inch)", "Angle (deg)", "Angle (rad)", "ArcLength (inch)", "Polar Area (sq. inch)");
System.out.printf("%13d%14d", radius01, angledeg01);
double anglerad01 = radius01 * (Math.PI / 180.0f);
}
}
All you have to do is convert Math.PI to a float since it is a double and not a float:
float anglerad01 = (radius01 * ((float)Math.PI / 180.0f));
The reason we need to do this conversion is because, while both floats and doubles are data types that represent decimals, they are not the same data type since doubles are more precise.
Math.PI gives you a constant in the form of a double, and so without casting to a float, you divide the double by a double, giving you a double, and then multiply it by an int to get a double. This leads you to be giving a float variable the value of a double.
However, once you cast Math.PI to a float, your final value will also be a float, making the variable legal.
First I read it wrong, I made the suggestion on the bases that Math.toRadians you are not able to use in your program due to some error.
So now its for what you have asked I hope.
1.data type double for anglerad01
2.As the expression will result a double its obvious as here we used Math.Pi.
3.float data type cannot take value of double data type.
4.So double anglerad01 should be used.
Also, for Radians = (Degrees × π)/180° . Degree is used to calculate radian not radius of circle.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("1st: Please enter a radius (integer) :");
int radius01 = input.nextInt();
System.out.println("1st: Please enter angle (in degrees between 0 and 360) :");
int angledeg01 = input.nextInt();
input.close();
double anglerad01 = radius01 * (Math.PI / 180.0f);
System.out.printf("%s%14s%15s%19s%24s\n", "Radius (inch)", "Angle (deg)", "Angle (rad)", "ArcLength (inch)", "Polar Area (sq. inch)");
System.out.printf("%13d%14d%18f", radius01, angledeg01, anglerad01 );
}

My separate method keeps returning the wrong value

I'm using my weight as a value of 180 to find my weight in lbs on planets other than earth with a formula to find weight using mass and surface gravity. The problem I'm facing is that whenever I call this method, the weight value returns as 180 all 8 times the method is called. In my code I have weight being calculated with (mass * roundedSG)/433... It shouldn't return as 180. I don't know how to fix this, I've been trying for a couple hours. The for loop is in a different method, I'm doing this for home work by the way, any help would be appreciated to just try and fix this problem of mine. Thanks!
public static double weight(double sGravity, double w)
{
double roundedSG = sGravity / 10;
double mass = (w * 433.59237)/roundedSG;
double weight = (mass * roundedSG)/433.59237;
return weight;
}
for(int i = 0; i < planetSurfaceGravity.length; i++)
{
weightOnPlanets[i] = weight(planetSurfaceGravity[i], weightLbs);
System.out.println(weightOnPlanets[i]);
}
}
I think your math in weight() is incorrect. It looks like weight is actually returning the following:
(w * 433/roundedSG)*roundedSG/433.
The 433s and roundedSGs cancel, and you're just returning w, which I'm guessing is 180?
I renamed your variables and added a constant which makes the code as written a bit clearer:
private static final double GRAMS_PER_POUND = 433.59237;
public static double weight(double sGravity, double weightLbs)
{
double roundedSG = sGravity / 10;
double mass = (weightLbs * GRAMS_PER_POUND)/roundedSG;
double weight = (mass * roundedSG)/GRAMS_PER_POUND;
return weight;
}
So your mass on earth, which is converted to grams, is being divided by the gravity of whatever planet you're checking. Change the mass calculation to be
double mass = weightLbs * GRAMS_PER_POUND;
Then the weight calculation should be ok as is, returning the weight on the other planet converted back from grams to pounds.
You weight method calculation are incorrect. the result of it returns only w which you pass as weightLbs (= 180).
Correct Weight Formula is:
weight = (mass*gravity);
Change from:
double weight = (mass * roundedSG)/433.59237;
To:
double weight = mass * roundedSG;

I want to calculate the distance between two points in Java

OK, so I've written most of a program that will allow me to determine if two circles overlap.
I have no problems whatsoever with my program aside from one issue: the program won't accept the code I've written for the distance between the two center points. I can figure out the if/else logic to tell the user what happens depending on the value of distance later, but I want to know what's wrong now. Eclipse, the program I'm coding on, is telling me that distance should be resolved to an array, but I've already told you that it's an int.
Here is my code:
package circles;
import java.util.Scanner;
public class MathCircles {
// variable for the distance between the circles' centers
public static int distance;
// variable for the lengths of the radii combined
public static int radii;
public static void main(String[] args) {
// Get the x-value of the center of circle one
System.out.println("What is the x-coordinate for the center of circle one?");
Scanner keyboard = new Scanner(System.in);
int x1 = keyboard.nextInt();
//Get the y-value of the center of circle one
System.out.println("What is the y-coordinate for the center of circle one?");
Scanner keyboard1 = new Scanner(System.in);
int y1 = keyboard1.nextInt();
//Get the radius length of circle one.
System.out.println("How long is circle one's radius?");
Scanner keyboard2 = new Scanner(System.in);
int r1 = keyboard2.nextInt();
// Get the x-value of the center of circle two.
System.out.println("What is the x-coordinate for the center of circle two?");
Scanner keyboard3 = new Scanner(System.in);
int x2 = keyboard3.nextInt();
//Get the y-value of the center of circle two.
System.out.println("What is the y-coordinate for the center of circle two?");
Scanner keyboard4 = new Scanner(System.in);
int y2 = keyboard4.nextInt();
//Get the radius length of circle two.
System.out.println("How long is circle two's radius?");
Scanner keyboard5 = new Scanner(System.in);
int r2 = keyboard5.nextInt();
/*
* OK, so now I have the location of the two circles' centers,
* as well as the lengths of their radii.
* The circles are intersecting IF THE DISTANCE BETWEEN THE TWO CENTERS
* IS EQUAL TO OR LESS THAN THE COMBINED LENGTHS OF THE RADII.
* Now I need to get some math done.
*/
//calculate the combined lengths of the radii
radii = r1 + r2;
//calculate the distance
distance = Math.sqrt((x1-x2)(x1-x2) + (y1-y2)(y1-y2));
}
}
Based on the #trashgod's comment, this is the simpliest way to calculate distance:
double distance = Math.hypot(x1-x2, y1-y2);
From documentation of Math.hypot:
Returns: sqrt(x²+ y²) without intermediate overflow or underflow.
Unlike maths-on-paper notation, most programming languages (Java included) need a * sign to do multiplication. Your distance calculation should therefore read:
distance = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
Or alternatively:
distance = Math.sqrt(Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2));
This may be OLD,
but here is the best answer:
float dist = (float) Math.sqrt(
Math.pow(x1 - x2, 2) +
Math.pow(y1 - y2, 2) );
Based on the #trashgod's comment, this is the simpliest way to calculate >distance:
double distance = Math.hypot(x1-x2, y1-y2);
From documentation of Math.hypot:
Returns: sqrt(x²+ y²) without intermediate overflow or underflow.
Bob
Below Bob's approved comment he said he couldn't explain what the
Math.hypot(x1-x2, y1-y2);
did. To explain a triangle has three sides. With two points you can find the length of those points based on the x,y of each. Xa=0, Ya=0 If thinking in Cartesian coordinates that is (0,0) and then Xb=5, Yb=9 Again, cartesian coordinates is (5,9). So if you were to plot those on a grid, the distance from from x to another x assuming they are on the same y axis is +5. and the distance along the Y axis from one to another assuming they are on the same x-axis is +9. (think number line) Thus one side of the triangle's length is 5, another side is 9. A hypotenuse is
(x^2) + (y^2) = Hypotenuse^2
which is the length of the remaining side of a triangle. Thus being quite the same as a standard distance formula where
Sqrt of (x1-x2)^2 + (y1-y2)^2 = distance
because if you do away with the sqrt on the lefthand side of the operation and instead make distance^2 then you still have to get the sqrt from the distance. So the distance formula is the Pythagorean theorem but in a way that teachers can call it something different to confuse people.
You need to explicitly tell Java that you wish to multiply.
(x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)
Unlike written equations the compiler does not know this is what you wish to do.
You could also you Point2D Java API class:
public static double distance(double x1, double y1, double x2, double y2)
Example:
double distance = Point2D.distance(3.0, 4.0, 5.0, 6.0);
System.out.println("The distance between the points is " + distance);
Math.sqrt returns a double so you'll have to cast it to int as well
distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

How do I write a Java program that calculates the distance between two points on earth?

I know how to start it out and I know how to put in the scanners and everything, but in school, I've never really learned about longitude and latitude formulas and how to convert those points into radians. So I'm pretty much stuck on this Java problem. Here is what I have so far:
import java.util.*;
class DistanceCalculator {
// Radius of the earth in km; this is the class constant.
public static final double Radius = 6372.795;
/**
* This program computes the spherical distance between two points on the surface of the Earth.
*/
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
intro();
System.out.print("Longitude (degrees.minutes) ");
double Longitude = console.nextDouble();
System.out.print("Latitude (degrees.minutes) ");
double Latitude = console.nextDouble();
}
public static double distFrom(double lat1, double lng1, double lat2, double lng2);
double Latitude = Math.toRadians(...);
}
public static void intro() {
System.out.println("This program computes the spherical distance between two points on the surface of the Earth.");
System.out.println("\tPlease start by entering the longitude and the latitude of location 1.");
}
}
In Java IDE, they say that Longitude and Latitude points (the ones underneath the intro();) are not used, and I know why, since I haven't really defined them yet.
I know I'm missing the formula for longitude and latitude. In my book, it wants me to use the spherical law of cosines, and since I've never learned this at school, no matter how hard I study the formula from the websites I sought out, I don't know how to transfer that into Java language.
Another problem is, how do I transfer degrees and minutes from a longitude/latitude point into radians? Do I have to use Math.toRadians thing? Oh yeah and also, my answer has to be in kilometers.
Updated: The math functions some of you guys are talking about confuses me greatly. In school (I'm a high schooler), even at Math IB SL, my teacher has never taught us how to find long/lat. points...yet. So it's hard for me to grasp. Since the spherical law of cosines formula is online, do I basically just take that formula and convert it into "java language" and plug it into my program?
The key word you need to search for is the "Haversine formula".
An easier to understand method, but one which is not quite so accurate for small distances, is to recall that the angle between two vectors A and B can be calculated using the dot product:
A ⋅ B = |A| * |B| * cos(theta)
so if you convert your polar lat/long pairs into 3D cartesian coordinates (and yes, you'll need to use Math.toRadians(), Math.cos() and Math.sin() to do that, and then calculate the dot product, you'll then get cos(theta), so use Math.acos() to get theta.
You can then work out the distance simply as D = R * theta, where R is the radius of the Earth, and theta remains in radians.
I suggest to read more about WGS84.
Mathematical explanations here.
You may look at this link for the logic.
http://aravindtrue.wordpress.com/2009/06/30/calculate-distance-using-latitude-and-longitude-php-mysql/
Function in PHP... I don't know Java. So some one edit my post. Here is the PHP function:
function getDistanceBetweenPointsNew($latitude1, $longitude1,
$latitude2, $longitude2, $unit = 'Mi')
{
$theta = $longitude1 - $longitude2;
$distance = (sin(deg2rad($latitude1)) *
sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) *
cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
$distance = acos($distance);
$distance = rad2deg($distance);
$distance = $distance * 60 * 1.1515;
switch($unit)
{
case 'Mi': break;
case 'Km' : $distance = $distance *1.609344;
}
return (round($distance,2));
}
also to get value from MySQL database:
Calculate distance given 2 points, latitude and longitude
I tried to create a java function, I don't know if it work or not.
try this. If any one can help, try edit my java code.
import java.math.BigDecimal;
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
public static double distFrom(double lat1, double lng1, double lat2, double lng2, String unit)
{
double theta = lng1 - lng2;
double distance = (
Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
)+(
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta))
);
distance = Math.acos(distance);
distance = Math.toDeg(distance);
distance = distance * 60 * 1.1515;
switch(unit)
{
/* Mi = miles, Km = Kilometers */
case "Mi" :
break;
case "Km" :
distance = distance *1.609344;
break;
}
distance = round(distance, 2, BigDecimal.ROUND_HALF_UP);
return distance;
}
import java.util.*;
public class SphericalDistance {
public static void main(String[] args){
System.out.println(" This program computes the spherical distance\n between two points, 1 and 2.");
System.out.println(" Please enter the latitude and longitude for \n each point as a pair of integers, degrees \n followed by minutes:");
System.out.print("Latitude 1:");
Scanner s=new Scanner(System.in);
double latangledeg = s.nextDouble();
double latanglemin = s.nextDouble()/60;
double phideg = latangledeg + latanglemin;
double phi1 = phideg * Math.PI/180;
System.out.print("Longitude 1:");
double lonangledeg = s.nextDouble();
double lonanglemin = s.nextDouble()/60;
double lambdadeg = lonangledeg + lonanglemin;
double lambda1 = lambdadeg * Math.PI/180;
System.out.println("Latitude 2:");
double latangledeg2 = s.nextDouble();
double latanglemin2 = s.nextDouble()/60;
double phideg2 = latangledeg2 + latanglemin2;
double phi2 = phideg2 * Math.PI/180;
System.out.println("Longitude 2:");
double lonangledeg2 = s.nextDouble();
double lonanglemin2 = s.nextDouble()/60;
double lambdadeg2 = lonangledeg2 + lonanglemin2;
double lambda2 = lambdadeg2 * Math.PI/180;
double lambdaf = lambda2 - lambda1;
double angdistance = Math.acos(Math.sin(phi1)*Math.sin(phi2) + Math.cos(phi1)*Math.cos(phi2)*Math.cos(lambdaf));
System.out.println("Angular Distance = " + angdistance + " radians");
int distancekm = (int)(angdistance * 6372.795);
int distancemi = (int) (distancekm * .621371);
System.out.println("Distance = " + distancekm + " kilometers");
System.out.println("Distance = " + distancemi + " miles");
s.close();
}
}

Java - How to round up float (or BigDecimal ) value by 0.5?

Seems simple question but I really suck at math and few examples online I've searched seems not working for me. (the result just return the same value as input etc)
For instance.. but its in C not Java
Round to Next .05 in C
So my goal is I have %.1f format float or double or big decimal and wanting to round it up to nearest .5
example:
1.3 --> 1.5
5.5 --> 5.5
2.4 --> 2.5
3.6 --> 4.0
7.9 --> 8.0
I tried following example but didn't work :( below just output 1.3 which is original value. I wanted it to be 1.5
public class tmp {
public static void main(String[] args) {
double foo = 1.3;
double mid = 20 * foo;
System.out.println("mid " + mid);
double out = Math.ceil(mid);
System.out.println("out after ceil " + out);
System.out.printf("%.1f\n", out/20.0);
}
}
Here's a simple method:
public static float roundToHalf(float x) {
return (float) (Math.ceil(x * 2) / 2);
}
This doubles the value, takes its ceiling, and cuts it back in half.
Multiplying (and later dividing) by 2, not 20, should do the trick.
double nearestPoint5 = Math.ceil(d * 2) / 2;
The below formula does not work well for number like 2.16
public static float roundToHalf(float x) {
return (float) (Math.ceil(x * 2) / 2);
}
The correct answer should be 2.0, but the above method gives 2.5
The correct code should be:
public static double round(float d)
{
return 0.5 * Math.round(d * 2);
}
See the Big Decimal Javadoc about why a String is used in the constructor
public static double round(double d, int decimalPlace){
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
Without using a function, you can do
double rounded = (double)(long)(x * 2 + 0.5) / 2;
Note: this will round towards infinity.
Some of the other answers round incorrectly (Math.round should be used, not Math.floor or Math.ceil), and others only work for rounding to 0.5 (which is what the question asked, yes). Here's a simple method that correctly rounds to the nearest arbitrary double, with a check to assure that it's a positive number.
public static double roundToNearest(double d, double toNearest) {
if (toNearest <= 0) {
throw new IllegalArgumentException(
"toNearest must be positive, encountered " + toNearest);
}
return Math.round(d/toNearest) * toNearest;
}

Categories