( 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);
Related
I am trying to have a union of regular expression and subtraction,I am able work range only like. String regex = "[1-3[5-7]]"; but need different type of numbers with range and at the same time union also like String regex = "\b([1-9]|[1-4][0-9]|5[0-5]&&[191])\b"; In this line am able to match 1 to 55 and also match 191.it is not working.Can any one give the suggestion where the problem getting. I tried for numeric range like below.
public class NumericRangeRegex {
public String baseRange(String num, boolean up, boolean leading1) {
char c = num.charAt(0);
char low = up ? c : leading1 ? '1' : '0';
char high = up ? '9' : c;
if (num.length() == 1)
return charClass(low, high);
String re = c + "(" + baseRange(num.substring(1), up, false) + ")";
if (up) low++; else high--;
if (low <= high)
re += "|" + charClass(low, high) + nDigits(num.length() - 1);
return re;
}
private String charClass(char b, char e) {
return String.format(b==e ? "%c" : e-b>1 ? "[%c-%c]" : "[%c%c]", b, e);
}
private String nDigits(int n) {
return nDigits(n, n);
}
private String nDigits(int n, int m) {
return "[0-9]" + String.format(n==m ? n==1 ? "":"{%d}":"{%d,%d}", n, m);
}
private String eqLengths(String from, String to) {
char fc = from.charAt(0), tc = to.charAt(0);
if (from.length() == 1 && to.length() == 1)
return charClass(fc, tc);
if (fc == tc)
return fc + "("+rangeRegex(from.substring(1), to.substring(1))+")";
String re = fc + "(" + baseRange(from.substring(1), true, false) + ")|"
+ tc + "(" + baseRange(to.substring(1), false, false) + ")";
if (++fc <= --tc)
re += "|" + charClass(fc, tc) + nDigits(from.length() - 1);
return re;
}
private String nonEqLengths(String from, String to) {
String re = baseRange(from,true,false) + "|" + baseRange(to,false,true);
if (to.length() - from.length() > 1)
re += "|[1-9]" + nDigits(from.length(), to.length() - 2);
return re;
}
public String run(int n, int m) {
return "\\b0*?("+ rangeRegex("" + n, "" + m) +")\\b";
}
public String rangeRegex(String n, String m) {
return n.length() == m.length() ? eqLengths(n, m) : nonEqLengths(n, m);
}
}
I think you are on the wrong track. You should simply extract and parse the numeric values and do the calculation in your regular programming language, as recommended by Patrick.
You can still create a wrapper class that helps to check numeric ranges using a simple function like
public static boolean between(int i, int minValueInclusive, int maxValueInclusive) {
return (i >= minValueInclusive && i <= maxValueInclusive);
}
or use commons.lang.Range:
Range<Integer> myRange = Range.between(1, 55);
if (myRange.contains(value)){
// do something
}
Based on conditions Ill try for union and subtraction is `^(?!250)0*?([0-9]|2(5([0-5])|[0-4][0-9])|1[0-9]{2}|[1-9][0-9]|2000)$. In this we are matching 1 to 255 range and 2000 numeric number(union) and for negate 250(subtraction).It's working fine.
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
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));
}
class Box
{
// Instance Variables
double length ,ipsos ;
double width ,mikos ;
double height ,platos;
// Constructors
public Box ( double side )
{
width = side ;
height = side ;
length = side ;
}
public Box ( double x , double y , double z)
{
platos = y ;
ipsos = z;
mikos = x ;
}
// Methods
double calculate(double praksi)
{
return 2 * ( width * height +
width * length +
height * length ) ;
}
double volume(double emvadon)
{
return platos*ipsos*mikos ;
}
}
In the upper code, how can I make a toString() method, so I can return the values of volume and calculate ???
Im new with java so be as simple as you can please
Not too sure what the parameters of the methods 'calculate', 'volme' are for?
If you're looking to override the default toString method, so when you call System.out.println(new Box(1,2,3)): it prints out the volume, and value calculate returns for the box then the following should work:
Box b = new Box(1,2,3);
System.out.println(b);
Then the following should work:
#Override
public String toString()
{
return "Volume: " + volume(0.0) + ", calculate: " + calculate(0.0);
}
This would print the volume and whatever calculate returns, both clearly labelled.
Add this method to your class (to override the toString() method):
#Override
public String toString() {
return "Volume: " + volume(1) + "\n Calculate: " + calculate(1);
}
Note: #Override is optional: it's just communication and making sure you receive an error if you misspell the overridden method (toString()).
Also, why do you have parameters for volume and calculate if you don't use them? That's why I passed them a random number like 1 because it apparently doesn't matter what they are.
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.