cannot convert from float to double? - java

The formula to calculate the area of a circumference is defined as x =
π . R2. Considering to this problem that π = 3.14159:
Calculate the area using the formula given in the problem description.
Input The input contains a value of floating point (double precision),
that is the variable R.
And for an input of 2, I should be getting x=12.5664 rounded by one number.
I tried using this simple code, but I couldn't remember what to do with the "cannot convert from double to float" error. It's been half a year since I coded.
package TEST;
import java.util.Scanner;
public class TEST {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// let A be radius
float A = scanner.nextFloat();
float A_2 = A * A;
// let B be Pi
double B = 3.14159;
// let x be circumference
float x = A_2 * B;
System.out.printf("x= %.4f" + x);
}}

The cause of the compilation error is the following assignment:
float x = A_2 * B;
where B is of type, double and therefore the result of the product will of type, double which can not be accommodated into a variable of type, float. Remember: double requires 8 bytes of space whereas a float variable can accommodate only 4 bytes.
After correcting this compilation error, you will encounter a runtime error because you have used a plus sign (+) instead of a comma (,) inside the printf statement.
Apart from this,
Always follow Java naming conventions e.g. A should be a and A_2 should be a2 following the conventions.
You can use Math.PI instead of using your own value for PI.
The following code incorporates these changes:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// let a be radius
float a = scanner.nextFloat();
float a2 = a * a;
// let b be PI
double b = Math.PI;
// let x be circumference
double x = a2 * b;
System.out.printf("x= %.4f", x);
}
}
A sample run:
2
x= 12.5664

You could try:
double A_2Converted = (double) A_2;
and use that.
source: Convert float to double without losing precision

Related

univariate, nonlinear optimisation / solver in Apache Commons - how to get started?

I'm having difficulty even beginning to solve this problem. All examples that I have found are either too simple or way too complex to digest.
I want to to find the value S given a series of inputs. The function is univariate but non-linear. S will always be between -3 .. 3.
I would like to use the Apache Commons library, as I have had prior experience in other sections of that code.
For each time I want to solve my problem, I know the following information:
double R =250.0;
double om1 = 5.0;
double om2 = 15.0;
double th21 = 29.07965;
double th22 = 29.69008;
double D_obs = th21 - th22;
The actual values will change between solutions, but they are fixed for any one particular solution.
The value I want to find is:
double S = 0.0;
such that
double d1 = delta(R,om1,th21,S);
double d2 = delta(R,om2,th22,S);
double D_calc = d1 - d2;
have values to make
double minme = Math.abs(D_obs - D_calc);
a minimum, or alternately, solve
double minme = D_obs - D_calc;
where minme=0.
The function delta is defined as
public static double delta(double R, double om, double th2, double s)
{
if(Math.abs(s) <= 0.0001) //is the displacement == 0?
{
return 0.0;
}
else
{
return Math.toDegrees((-1*Cos(th2)*s-R*Sin(om)+Sqrt(-1*Math.pow(Cos(th2),2)*Math.pow(s,2)+2*Cos(th2)*Sin(om)*R*s-Math.pow(Cos(om),2)*Math.pow(R,2)+Math.pow(R,2)+2*Math.pow(s,2)))/(Sin(th2)*s));
}
}
where, for example, Cosis defined elsewhere as Math.cos(Math.toRadians(val))
Where/what can I read/do to get a start on this problem?
I found an answer I could work with: Newton-Raphson method using the Math.Commons library
The key code is
public static void main(String args[])
{
//setup all variables
final double R =(new Double(args[0])).doubleValue(); //=250.0;
final double om1 =(new Double(args[1])).doubleValue(); //= 5.0;
final double om2 =(new Double(args[2])).doubleValue(); //= 15.0;
final double th21=(new Double(args[3])).doubleValue(); //= 29.07965;
final double th22=(new Double(args[4])).doubleValue(); //= 29.69008;
final double D_obs = th21 - th22;
BisectionSolver solver = new BisectionSolver();
UnivariateFunction f = new UnivariateFunction()
{
public double value(double s) {
return ((delta(R,om1,th21,s)-delta(R,om2,th22,s)) - (D_obs));
}
};
System.out.printf("The speciment offset is %.3f mm.\n", solver.solve(1000, f, -3, 3));
}

Java :calculate the circle diameter and

this is a Class about calculating diameter,circumference and area of circle that user enter radius value and it gives him diameter,cirucumf... ,
this is the class code:
package circle;
import java.util.Scanner;
public class Circle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int radius=0;
int diameter;
int circumference ;
int area;
int Pi;
Pi=(int) 3.14;
area = (int) (radius*radius*Pi);
circumference =(int)(radius*2*Pi);
diameter = (int)(radius*2);
System.out.print("Enter radius value:");
radius=input.nextInt();
System.out.printf("area is %d%n" , area);
System.out.printf("diameter is %d%n", diameter);
System.out.printf("circumference is %d%n", environment);
}
}
this is what output gives me :
Enter radius value: (for exmaple) 4
area is 0 // (real value is 50.24)
diameter is 0 // (8)
circumference is 0 //(25.12)
what is the code problem?
or how can i fix it?
You read the radius AFTER computing area/environment(?)/diameter. Furthermore, your values are int variables, which also means that your value for pi is just 3. I suggest you correct the order of the statements, and start using double instead of int.
"environment" will be replaced by "circumference". As your excepted output is decimal value. So use float/double instead of int. In your program you are calculating diameter,circumference and area after initialising the value of radius(radius=0) but before getting the value of radius(radius=4). I have modified your code. It seem help you.
package circle;
import java.util.Scanner;
public class Circle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int radius=0;
float diameter;
double circumference ;
double area;
double Pi;
Pi= 3.14;
System.out.print("Enter radius value:");
radius=input.nextInt();
area = (radius*radius*Pi);
circumference =(radius*2*Pi);
diameter = (radius*2);
System.out.printf("area is " + area);
System.out.printf("\ndiameter is "+ diameter);
System.out.printf("\ncircumference is "+ circumference);
}
}
you are calculating the values area/environment(?)/diameter before getting and initializing the radius input.And at that time the default value for radius is set which is 0. Hence it is giving the results of all the parameters as 0.So you will have to re order your code as below:
System.out.print("Enter radius value:");
radius=input.nextInt();
area = (int) (radius*radius*Pi);
environment=(int)(radius*2*Pi);
diameter = (int)(radius*2);
System.out.printf("area is %d%n" , area);
System.out.printf("diameter is %d%n", diameter);
System.out.printf("environment is %d%n", environment);

Pythagoras tree in Java: How do I calculate the third point of the triangle?

Dear more advanced programmers,
I have to programm a Pythagoras tree (see: https://en.wikipedia.org/wiki/Pythagoras_tree_(fractal) ) and I want to take a step forward, but I just can't.
I want to create the 3rd point of the triangle, but after 2 days of searching in books, internet, my head, etc., I just did not find a solution. Well, I have a solution, but it wont work for the recursive step and I don't know how to create the 3rd and 4th point of the following squares.
I want my programm to draw the step 1 of the tree.
Here's my code for the calculation so far:
public static void main(String[] args) {
double ax;
double ay;
double bx;
double by;
double cx;
double cy;
double dx;
double dy;
ax = 0.25;
ay = 0.75;
bx = 0.25;
by = 0.25;
cx = 0.75;
cy = 0.25;
dx = 0.75;
dy = 0.75;
StdDraw.line(ax,ay,bx,by); // ax etc. are doubles
StdDraw.line(bx,by,cx,cy);
StdDraw.line(cx,cy,dx,dy);
StdDraw.line(dx,dy,ax,ay);
double alpha;
double beta;
double random = 0.0;
while(random <= 0.3 || random >= 0.6){ //random angular between 30&60
random = Math.random();
}
random = random*100; //to make it an angular
alpha = random; //set alpha to this angular
beta = 90-alpha;
double sinusBeta= Math.toRadians(beta);
double sinusAlpha= Math.toRadians(alpha);
sinusBeta = Math.sin(sinusBeta);
sinusAlpha = Math.sin(sinusAlpha);
double side_b = 0.5*sinusBeta;
double side_a = 0.5*sinusAlpha;
double hypothenuse = Math.sqrt((side_b*side_b)+(side_a*side_a));
double p = (side_a*side_a)/hypothenuse; //to get h of the triangle
double q= (side_b*side_b)/hypothenuse;
double h = Math.sqrt(p*q);
double triangleTop_x = ax+q;
double triangleTop_y = ay+h;
StdDraw.line(ax, ay, triangleTop_x , triangleTop_y);
StdDraw.line(dx, dy, triangleTop_x , triangleTop_y);
}
I know that this is not the right way to get the last triangle point cause it has the condition that the hypothenuse is exactly in the direction of the x-axis. Which is not true for step two anymore, so a recursive method would not behave as it should. I wrote all the code by my own, I know it is not the best one, but it would be awesome to get an idea of how I can build the triangle and the following squares not direction-dependent.
Thank you so much in advance for any ideas that may help!

Euler Method in Java, Variable Initial Condition

How would I write the Euler method in Java for a variable initial condition? For example, the initial condition that y(w)=0.
The equation I'm trying to solve is:
dy/dx = (y-sqrt(x^2 + y^2))/x
My initial code is simple.
import java.lang.Math;
public class euler
{
public static void main(String arg[])
{
int N = 10;
double h = 1.0/N;
double x0 = w; //This is what I would like to put in
double y0 = 0;
double x = x0, y = y0;
for (int i=0;i < N;i++)
{
y += h*f(x, y);
x += h;
System.out.println("x, y = " + x + ", " + y);
}
}
static double f(double x, double y)
{
return((y-Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)))/x);
}
}
My code should work for any kind of integer value of x0, but how could I get it to work for a variable w?
You get not only one solution, you get a family of solutions parametrized by the initial condition. Through every point (x0,y0) there is a solution, some, but not all, will give the same solution.
Thus y(w)=0 resp. the pair (x0=w, y0=0) will give a solution for every w, there is nothing to solve to get a specific value of w.
?? Could w stand for omega and that for infinity ?? That would be a valid question, to control the asymptotic behavior.
The only critical point of this problem is x=0, and even that only for y(0)<0, since then the differential equation has a singularity.

new error: Actual and formal argument lists differ in length

Trying to finish an assignment for my first year comp class. So far everything's been okay, but I can't figure this one error out. I was wondering if anyone could help out here? I tried changing my variables to doubles and obviously it didnt work.
import java.util.Scanner;
public class CellPhoneProgram {
public static Scanner keyboard = new Scanner(System.in);
//declare x and y coordinates for each city
public static double xa = 100, xb = 100, xc = 340, xd = 230, ya = 360, yb = 360, yc = 250, yd = 140;
public static int getRange(int city) {
int range = 0;
System.out.println("What is the maximum distance (in km) from the center of City " + city + " that you may travel without losing service?");
range = keyboard.nextInt();
return range;
}
/* ERROR OCCURS HERE */
public static double distance(double xf, double xi, double yf, double yi) {
double distance = 0;
distance = Math.sqrt((Math.pow(xf - xi)) - (Math.pow(yf - xi)));
return distance;
}
public static void main(String[] args) {
int city1, city2, city3, city4;
double distance1, distance2, distance3;
System.out.println("Welcome to the Cell Phone Service Program, where you enter the range of service from four cities," +
" and we calculate whether or not you lose service.");
//get range from function
city1 = getRange(1);
city2 = getRange(2);
city3 = getRange(3);
city4 = getRange(4);
System.out.println(city3);
//calculate distances from cities
distance1 = distance(xb, xa, yb, ya);
distance2 = distance(xc, xb, yc, yb);
distance1 = distance(xd, xc, yd, yc);
System.out.println(distance1);
}
}
here's a look at the error:
File: C:\Users\Katie\Documents\Homework\CellPhoneProgram.java [line: 16]
Error: method pow in class java.lang.Math cannot be applied to given types;
required: double,double
found: double
reason: actual and formal argument lists differ in length
File: C:\Users\Katie\Documents\Homework\CellPhoneProgram.java [line: 16]
Error: method pow in class java.lang.Math cannot be applied to given types;
required: double,double
found: double
reason: actual and formal argument lists differ in length
This code is definitely still in progress, sorry about the messiness and incomplete code and all that.
Math.pow() requires two arguments not one. I am guessing you want to raise to the second power so the second argument should be 2.
Math.sqrt((Math.pow(xf - xi,2)) - (Math.pow(yf - xi,2)));
See http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#pow%28double,%20double%29

Categories

Resources