how to get an Integer as result - java

I have created an application for android that takes three inputs and makes a calculation
else {
float result1 = (((new Float(input11.getText().toString())
+ new Float(input21.getText().toString()))/2));
float result2 = (new Float(input31.getText().toString());
if(result1<(result2 - 2)) {
result1 = result2-2;
float result=(float) ( (new Float(result1)*0.3)+(new Float(result2)*0.7));
vprosvasis.setText(Float.toString(result));
}
else if(result1>(result2 + 2)) {
result1=result2+2;
float result=(float) ( (new Float(result1)*0.3)+(new Float(result2)*0.7));
vprosvasis.setText(Float.toString(result));
}
else {
float result = (float) ((((new Float(input11.getText().toString())
+ new Float(input21.getText().toString()))/2)*0.3)
+ (new Float(input31.getText().toString())*0.7));
vprosvasis.setText(Float.toString(result));
}
}
Firstly,i would like the result in every statement to be e.x. 12.35 ,not 12,342323...
Secondly,i get in the same way vprosvasis2-vprosvasis7.i would like the final result that i print to be an integer and not a float..
float vprosvasisFloat = Float.parseFloat(vprosvasis.getText().toString());
float vprosvasisFloat2 = Float.parseFloat(vprosvasis2.getText().toString());
float vprosvasisFloat7 = Float.parseFloat(vprosvasis7.getText().toString());
float vprosvasisFloat5 = Float.parseFloat(vprosvasis6.getText().toString());
float vprosvasisFloat4 = Float.parseFloat(vprosvasis7.getText().toString());
float vprosvasisFloat3 = Float.parseFloat(vprosvasis6.getText().toString());
float vprosvasisFloat6 = Float.parseFloat(vprosvasis5.getText().toString());
float genikosvathmosoik = (( new Float(vprosvasis.getText().toString())
+ new Float(vprosvasis2.getText().toString())
+ new Float(vprosvasis3.getText().toString())
+ new Float(vprosvasis4.getText().toString())
+ new Float(vprosvasis5.getText().toString())
+ new Float(vprosvasis6.getText().toString())
+ new Float(vprosvasis7.getText().toString())) / 7);
moria2oik = (((new Float ((genikosvathmosoik*8)+(vprosvasisFloat * 1.3)+(vprosvasisFloat2 * 0.7))*100)));
moria3oik=(((new Float ((genikosvathmosoik*8)+(vprosvasisFloat4 * 1.3)+(vprosvasisFloat3 * 0.7))*100)));
moria5oik=(((new Float ((genikosvathmosoik*8)+(vprosvasisFloat7 *1.3)+(vprosvasisFloat6 * 0.7))*100)));
switch(spinner.getSelectedItemPosition()){
case 0:
show = new AlertDialog.Builder(mContext).setTitle(R.string.app_name)
.setMessage("1o : -\n2o : "
+ moria2oik + "\n3o : "
+ moria3oik + "\n4o : "
+ moria2oik + "\n5o : "
+ moria5oik)
.setPositiveButton("OK", null).show();
break;

If I understand the question correctly, you should look into the Math class of Java. Here is the developer doc.
The math class can do almost everything when it comes to manipulating a float or double.
The other class you might want to look at is DecimalFormat which can do exactly what is says, format decimals. :) That is available here.

You could take a look at java.text.NumberFormat. It will provide you methods to format your results in a user-friendly way, and also helps parsing according to the user's locale.

Related

Exponential to decimal java android

I have a trouble, i'm doing calculators for school and i need to convert "E" to decimal in answer.
I have: 6.67E-11
I want: 6.67 * 10^-11
double m1 = Double.parseDouble(et1.getText().toString());
double m2 = Double.parseDouble(et2.getText().toString());
double R = Double.parseDouble(et3.getText().toString());
double answer = (6.67 * Math.pow(10, -11)) * ((m1 * m2) / sqrt(R));
tv_answer.setText(answer + "");
I can add this:
NumberFormat formatter = new DecimalFormat("###.####################");
String f = formatter.format(answer);
and edit:
tv_answer.setText(f + "");
But i will get something like this: 0.0000000000667. That's not cool :/
Not the best way, but you can try this.
BigDecimal d1 = new BigDecimal("0.0000000000000096");
DecimalFormat df = new DecimalFormat("0.0E0");
System.out.print(df.format(d1).replace("E"," * 10^"));
Output
9.6 * 10^-15
BigDecimal Example
double m1 = Double.parseDouble(et1.getText().toString());
double m2 = Double.parseDouble(et2.getText().toString());
double R = Double.parseDouble(et3.getText().toString());
double answer = BigDecimal.valueOf(6.67)
.multiply(BigDecimal.valueOf(Math.pow(10,-11)))
.multiply(BigDecimal.valueOf(m1).multiply(BigDecimal.valueOf(m2).divide(Math.sqrt(R),21,BigDecimal.ROUND_HALF_UP)))
.doubleValue();
tv_answer.setText(answer + "");

How do I pass updated parameter values back into the method from which they came?

I'm having trouble passing the updated values of initial_guess_1 and initial_guess_2 back into the GoldenSectionSearch method (I've attempted to have the method call itself until the terminating condition associated with the "if" is satisfied). My attempts at resolving this myself were influenced by what I found here:
https://softwareengineering.stackexchange.com/questions/286008/parameters-are-passed-by-value-but-editing-them-will-edit-the-actual-object-li
http://www.java-tutorial.com/java-tutorial/java-classes-methods/java-call-reference/
I'm still unable to figure out what I am doing wrong in trying to pass updated values back into the method. What am I doing wrong and how do I fix it? I'm a novice at programming and would like things broken down into the smallest,most easily understood terms possible.
public static double GoldenSectionSearch(double x_1, double x_2, double initial_guess_1,double initial_guess_2 ,double gradient_x, double gradient_y, double a,double a_0,double a_1,double a_2,double b_0,double b_1,double p,double N){
//Stuff
if(Math.abs((100*(x_2 - x_1*x_1)*(x_2 - x_1*x_1) + (1- x_1)*(1- x_1)) - (100*(initial_guess_2 - initial_guess_1*initial_guess_1)*(initial_guess_2 - initial_guess_1*initial_guess_1) + (1- initial_guess_1)*(1- initial_guess_1)) )/Math.abs(1+(100*(initial_guess_2 - initial_guess_1*initial_guess_1)*(initial_guess_2 - initial_guess_1*initial_guess_1) + (1- initial_guess_1)*(1- initial_guess_1))) >=0.50*Math.pow(10,-6)){
initial_guess_1=x_1;
initial_guess_2=x_2;
//Double Boxed_a = new Double(a);
Double Boxed_initial_guess_1 = new Double(initial_guess_1);
Double Boxed_initial_guess_2 = new Double(initial_guess_2);
initial_guess_1.GoldenSectionSearch(initial_guess_1);
initial_guess_2.GoldenSectionSearch(initial_guess_2);
gradient_x = (400*initial_guess_1*(initial_guess_1*initial_guess_1 - initial_guess_2) + 2*(initial_guess_1 -1));
gradient_y = (200*(initial_guess_2 - initial_guess_1*initial_guess_1));
GoldenSectionSearch(initial_guess_1,initial_guess_2,x_1, x_2, gradient_x, gradient_y, a, a_0, a_1, a_2, b_0, b_1, p,N);
} else{
double f_x=(100*(x_2 - x_1*x_1)*(x_2 - x_1*x_1) + (1- x_1)*(1- x_1));
System.out.print("alpha = " + a + " " + "x_1 = " + x_1 + " " + "x_2 = " + x_2 + " " + "f_x = " + f_x);
}
// Double Boxed_a = new Double(a);
return x_2;
}
You can't modify primitives. You have to create wrapper class with getters/setters
public class MyWrapperObject {
private double x_1;
private double x_2;
private double initial_guess_1;
private double initial_guess_2;
private double gradient_x;
private double gradient_y;
private double a;
private double a_0;
private double a_1;
private double a_2;
private double b_0;
private double b_1;
private double p;
private double N;
public double getX_1() {
return x_1;
}
public void setX_1(double x_1) {
this.x_1 = x_1;
}
/* The rest of getters/setters */
}
than pass it to your method and use it like
public static double GoldenSectionSearch(MyWrapperObject obj){
// ...
double initial_guess_1 = obj.get_initial_guess_1();
double initial_guess_2 = obj.get_initial_guess_2();
obj.setGradient_x(400*initial_guess_1*(initial_guess_1*initial_guess_1 - initial_guess_2) + 2*(initial_guess_1 -1));
// ...
}
There is also a question here on SO whether java is pass-by-reference or pass-by-value https://stackoverflow.com/a/40523/2022162

How to use standard SimpsonIntegrator in import org.apache.commons.math3.analysis.integration.SimpsonIntegrator;

public double evalute(double distance){
/**
* equation (3.2)
*/
this.from = 0;
this.to = distance;
this.n = 2;
return - 10 * Math.log10(Math.exp(-IntSimpson(this.from, this.to, this.n)));
}
There is IntSimpson() function i designed manually, but I want to use standard library! How can i do it and where it can be found?
If you want to actually use the integrator object, you need to call the integrate method, which takes an instance of UnivariateFunction. If you are on Java 8, this is a single-method interface, so it is automatically a functional interface. Thus, you can pass a lambda or a method reference, as in:
final SimpsonIntegrator si = new SimpsonIntegrator();
final double result = si.integrate(50, x -> 2*x, 0, 10);
System.out.println(result + " should be 100");
Otherwise, you have to create an implementation of the interface yourself, either by having a class implement it, or by using an anonymous class:
final double result = si.integrate(50, new UnivariateFunction() {
#Override public double value(double x) {
return 2*x;
}
}, 0, 10);
System.out.println(result + " should be 100");
It works!
final SimpsonIntegrator si = new SimpsonIntegrator();
final double result1 = si.integrate(10, x -> 2*Math.pow(x, 1), 0.0, 10.0);
System.out.println(result1 + " should be 100.0");
final double result2 = si.integrate(1000, x -> Math.sin(x), 0.0, Math.PI);
System.out.println(result2 + " should be 2.0000...");
Thanks Javier Martín !

Calculator in java displays double instead if int

Hey guys i am building a java calculator and everything works fine except the fact that i am doing calculations with double numbers.
The problem is that when i want to do 0.3 + 0.5 = 0.8 works fine, but when i do 6 + 6 = 12.0
How can i fix this so when the result is .0 at the end it displays an integer?
My code is:
public void actionPerformed(ActionEvent e) {
int j = 0;
r2 = Double.parseDouble(textField.getText());
if (option.equals("+")) {
result = r1 + r2;
}
if (option.equals("-")) {
result = r1 - r2;
}
if (option.equals("*")) {
result = r1 * r2;
}
if (option.equals("/")) {
result = r1 / r2;
}
textField.setText(result + " ");
}
Use a DecimalFormat object (see the documentation at http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html).
Example:
DecimalFormat df = new DecimalFormat("############.#");
System.out.println(df.format(result));
You can check if your result is int and if it is then then set its integer value to result like this.
public void actionPerformed(ActionEvent e) {
int j = 0;
r2 = Double.parseDouble(textField.getText());
if (option.equals("+")) {
result = r1 + r2;
}
if (option.equals("-")) {
result = r1 - r2;
}
if (option.equals("*")) {
result = r1 * r2;
}
if (option.equals("/")) {
result = r1 / r2;
}
if ((result == Math.floor(result )) && !Double.isInfinite(result )) {
textField.setText((int)(result) + " ");
} else textField.setText(result + " ");
}
You can just check if result has a whole number in it, like this:
if((int) result == result) {
textField.setText((int)result + " ");
} else {
textField.setText(result + " ");
}
EDIT
As #Hovercraft Full Of Eels said, you could put more thought into deciding, what is a whole number and what is not, especialy for case when result is something like 5.99999997 and simple casting to int will make 5 from such number.
final double epsilon = 1e-6;
if(Math.abs(Math.rint(myVal) - myVal) < epsilon) {
textField.setText(Math.round(myVal) + "");
} else {
textField.setText(String.format("%f", myVal));
}

Convert String "sin(pi*cos(pi*x*y))" to double

( I'm beginner )
double x = 0.5;
double y = 0.3;
String[]normal = {"x","y","cos","sin","avg"};
String[]complex = {"cos","sin","avg"};
char coordinate = (char) (new Random().nextInt(2) + 'x');
String result = "";
if(levels == 1){
String value1 = (normal[new Random().nextInt(normal.length)]);
if (value1.equals("sin") ||value1.equals("cos")){
result = value1 + "( pi *" + coordinate + ")";
}
else if(value1.equals("avg")){
result = value1 + "(" + coordinate + "," + coordinate + ")" ;
}
else{
result = value1 ;
}
}else{
String value = (complex[new Random().nextInt(complex.length)]);
if((value.equals("sin") ||value.equals("cos"))&&levels!=0 ){
result = value + "( pi *" + createFunction(levels - 1) + ")";
}
else if(value.equals("avg")&& levels !=0){
result = value +"(" + createFunction (levels - (levels-1)) + "," + createFunction (levels - (levels-1)) + ")" ;
}
else if(value.equals("avg")&& levels ==2){
result = value + "(" + createFunction (levels - 1) + "," + coordinate + ")" ;
}
else{
result = value ;
}
}
return result;
}
double functions = ....................... ;
result will be "sin(pi*cos(pi*x*y))" in String
how to calculate this string and keep in double functions
You are asking how to parse a string containing an arbitrary expression and then evaluate it to get a floating-point result.
That is quite difficult, requiring an expression parser, to convert the string into an expression tree, and an expression tree evaluator, to actually calculate the result.
You can do this using Groovy scripts. The trick is to evaluate your input as a Java-like expression:
public final class Test{
private static GroovyShell createMathShell() {
GroovyShell shell = new GroovyShell();
shell.evaluate("" +
"cos = {double x -> Math.cos(x)}\n" + // predefine functions as lambda
"sin = {double x -> Math.sin(x)}\n" + // expressions
"pi = Math.PI\n" // define pi
);
return shell;
}
public static void main(String[] args) {
GroovyShell shell = createMathShell();
// set values
shell.setVariable("x", 0);
shell.setVariable("y", 1);
// evaluate
double result = (Double) shell.evaluate("sin(pi*cos(pi*x*y))");
System.out.println(result);
}
}
Executing this code will print:
1.2246467991473532E-16
It would be wise to initialise a double and directly write the value into that variable.
Double answer = ....;
When you need the original value, just use the variable answer. When you need it as a string, just use:
String answer_string = String.valueOf(answer);
Or, for example:
System.out.println(String.valueOf(answer));
Math.sin and Math.cos methods will accept double values, and return a double. Simply write a method taking as arguments x and y to return the formula:
double myAlgorithm( double x, double y){
return Math.sin(Math.PI*Math.cos(Math.PI*x*y))
}
This will work passing x and y as int as it will be casted implicitly to double
double myAlgorithm( int x, int y){
return Math.sin(Math.PI*Math.cos(Math.PI*x*y))
}
And, if you want to pass Strings instead of types:
double myAlgorithm( String x, String y){
return Math.sin(Math.PI*Math.cos(Math.PI*(Double.parseDouble(x).doubleValue())*(Double.parseDouble(y).doubleValue())))
}
This should do it:
Double.valueOf(string);

Categories

Resources