Java Convert double to int - java

I have this code, and the input in the textfield is 50, so its output should be 25,
but there is a error, because no output
button_1.addActionListener(new ActionListener() {
String tfg = textField.getText().toString();
String tfc = textField.getText();
public void actionPerformed(ActionEvent e) {
if(textField.getText().toString().equals("0") ||
textField.getText().toString().equals("") ||
textField.getText().toString().equals(" ") ||
textField.getText().toString().matches("[a-zA-Z]+")) {
JOptionPane.showMessageDialog(Cow.this,
"Tree Amount Should Be 1 or More",
"Invalid Tree Amount",
JOptionPane.ERROR_MESSAGE);
}
if(!tfg.equals("0")) {
try {
int tfgg = Integer.parseInt(tfc);
int trcs = tfgg * 1;
double trcp = 1 / 2;
int trcc = (int) trcp * trcs;
System.out.println(new Integer(trcc).toString());
} catch (NumberFormatException se) {
}
}
}
});
I try to convert from my php to that code, here is my php code :
$doorSeed = $mount * 1;
$doorPrice = 1 / 2;
$doorConvert = $doorPrice * $doorSeed;
echo "Treasure Chest Seed = ".$doorSeed." Price : ".$doorConvert." World Lock <br>";

int trcc = (int) trcp * trcs;
Try this instead
int trcc = (int) (trcp * trcs);
You need to cast the complete expression [(trcp * trcs)] instead of just the first variable trcp to int. The other variable in the expression trcs is of double type, so the result of the expression become double. That is why you cast the complete expression. So your end result will be int
int tfgg = Integer.parseInt(tfc.trim()); // tfc = 4; tfgg = 4;
int trcs = tfgg * 1; // trcs = 4 * 1 = 5;
double trcp = 1.0 / 2; // trcp = 0.5;
int trcc = (int) (trcp * trcs); // trcc = (0.5 * 5) = (2.5) = 2;
System.out.println(trcc); // 2;
double trcp = 1.0 / 2;
Here make at least one value as double so the expression will be evaluated as double as suggested by #tunaki.
Also you don't need this statement in your code int trcs = tfgg * 1;.
Use like this:
String tfg ;
String tfc ;
public void actionPerformed(ActionEvent e) {
tfg = textField.getText();
tfc = textField.getText();
if(textField.getText().equals("0") || textField.getText().equals("") || textField.getText().equals(" ") || textField.getText().matches("[a-zA-Z]+")) {
JOptionPane.showMessageDialog(Cow.this,
"Tree Amount Should Be 1 or More",
"Invalid Tree Amount",
JOptionPane.ERROR_MESSAGE);
}
if(!tfg.equals("0")) {
try {
int tfgg = Integer.parseInt(tfc.trim()); // tfc = 4;
int trcs = tfgg; // trcs = 4 * 1 = 5
double trcp = 1.0 / 2; // trcp = 0.5
int trcc = (int) (trcp * trcs); // trcc = (0.5 * 5) = (2.5) = 2
System.out.println("HI: "+trcc);
} catch (NumberFormatException ignored) {
}

Your problem is at this line:
double trcp = 1 / 2;
This does not result in trcp = 0.5 but trcp = 0.0, because you are dividing integer values (and so are using integer division).
You should use the following code:
double trcp = 1.0 / 2;
to force division using doubles.
Other comments:
new Integer(trcc).toString() should be replaced with String.valueOf(trcc).
Avoid using empty catch statements: at minimum, log the exception
What's the point of this line: int trcs = tfgg * 1;?

Basically you have this (int)0.5 = 0.
In your case, trcp = 0.5 and is double, so when it's cast to integer the result is 0.
And when you do (int)a + b, the true operation with parenthesis for priority here is: ((int)a)+(b), so what you have to is the following:
int trcc = (int) (trcp * trcs);
instead of the following:
int trcc = (int) trcp * trcs;

Related

Exponential integral and gamma function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
In order to solve this problem, without iteration:
Recursion: Sum of series of n terms
calculating for a given n: 1 + 2*3 + 3*4*5 + 4*5*6*7 + ... +
n*(n+1)...(2n-1)
with this mathematical answer:
https://math.stackexchange.com/questions/1590673/formula-to-calculate-directly-1-23-345-4567-nn1-2n#1590687
It here a library in java to get Exponential integral and Gamma function ?
as in this formula:
Thanks
Apache Commons Math library has Gamma class.
I have adapted code from Exponential Integrals page from C to Java for Ei(x):
/**
*
*/
package wilx.math.exponential.integrals;
/**
* #author wilx
*/
public class ExponentialIntegrals
{
// Internally Defined Constants //
static final double DBL_EPSILON = Math.ulp(1.0);
static final double epsilon = 10.0 * DBL_EPSILON;
static final double DBL_MAX = Double.MAX_VALUE;
// //////////////////////////////////////////////////////////////////////////////
// double xExponential_Integral_Ei( double x ) //
// //
// Description: //
// The exponential integral Ei(x) is the integral with integrand //
// exp(t) / t //
// where the integral extends from -inf to x. //
// Note that there is a singularity at t = 0. Therefore for x > 0, the //
// integral is defined to be the Cauchy principal value: //
// lim { I[-inf, -eta] exp(-t) dt / t + I[eta, x] exp(-t) dt / t } //
// in which the limit is taken as eta > 0 approaches 0 and I[a,b] //
// denotes the integral from a to b. //
// //
// Arguments: //
// double x The argument of the exponential integral Ei(). //
// //
// Return Value: //
// The value of the exponential integral Ei evaluated at x. //
// If x = 0.0, then Ei is -inf and -DBL_MAX is returned. //
// //
// Example: //
// double y, x; //
// //
// ( code to initialize x ) //
// //
// y = xExponential_Integral_Ei( x ); //
// //////////////////////////////////////////////////////////////////////////////
public static double Exponential_Integral_Ei(final double x)
{
if (x < -5.0)
{
return Continued_Fraction_Ei(x);
}
if (x == 0.0)
{
return -DBL_MAX;
}
if (x < 6.8)
{
return Power_Series_Ei(x);
}
if (x < 50.0)
{
return Argument_Addition_Series_Ei(x);
}
return Continued_Fraction_Ei(x);
}
// //////////////////////////////////////////////////////////////////////////////
// static double Continued_Fraction_Ei( double x ) //
// //
// Description: //
// For x < -5 or x > 50, the continued fraction representation of Ei //
// converges fairly rapidly. //
// //
// The continued fraction expansion of Ei(x) is: //
// Ei(x) = -exp(x) { 1/(-x+1-) 1/(-x+3-) 4/(-x+5-) 9/(-x+7-) ... }. //
// //
// //
// Arguments: //
// double x //
// The argument of the exponential integral Ei(). //
// //
// Return Value: //
// The value of the exponential integral Ei evaluated at x. //
// //////////////////////////////////////////////////////////////////////////////
private static double Continued_Fraction_Ei(final double x)
{
double Am1 = 1.0;
double A0 = 0.0;
double Bm1 = 0.0;
double B0 = 1.0;
double a = expl(x);
double b = -x + 1.0;
double Ap1 = b * A0 + a * Am1;
double Bp1 = b * B0 + a * Bm1;
int j = 1;
a = 1.0;
while (fabsl(Ap1 * B0 - A0 * Bp1) > epsilon * fabsl(A0 * Bp1))
{
if (fabsl(Bp1) > 1.0)
{
Am1 = A0 / Bp1;
A0 = Ap1 / Bp1;
Bm1 = B0 / Bp1;
B0 = 1.0;
}
else
{
Am1 = A0;
A0 = Ap1;
Bm1 = B0;
B0 = Bp1;
}
a = -j * j;
b += 2.0;
Ap1 = b * A0 + a * Am1;
Bp1 = b * B0 + a * Bm1;
j += 1;
}
return (-Ap1 / Bp1);
}
// //////////////////////////////////////////////////////////////////////////////
// static double Power_Series_Ei( double x ) //
// //
// Description: //
// For -5 < x < 6.8, the power series representation for //
// (Ei(x) - gamma - ln|x|)/exp(x) is used, where gamma is Euler's gamma //
// constant. //
// Note that for x = 0.0, Ei is -inf. In which case -DBL_MAX is //
// returned. //
// //
// The power series expansion of (Ei(x) - gamma - ln|x|) / exp(x) is //
// - Sum(1 + 1/2 + ... + 1/j) (-x)^j / j!, where the Sum extends //
// from j = 1 to inf. //
// //
// Arguments: //
// double x //
// The argument of the exponential integral Ei(). //
// //
// Return Value: //
// The value of the exponential integral Ei evaluated at x. //
// //////////////////////////////////////////////////////////////////////////////
private static double Power_Series_Ei(final double x)
{
double xn = -x;
double Sn = -x;
double Sm1 = 0.0;
double hsum = 1.0;
final double g = 0.5772156649015328606065121;
double y = 1.0;
double factorial = 1.0;
if (x == 0.0)
{
return -DBL_MAX;
}
while (fabsl(Sn - Sm1) > epsilon * fabsl(Sm1))
{
Sm1 = Sn;
y += 1.0;
xn *= (-x);
factorial *= y;
hsum += (1.0 / y);
Sn += hsum * xn / factorial;
}
return (g + logl(fabsl(x)) - expl(x) * Sn);
}
static final double ei[] = { 1.915047433355013959531e2,
4.403798995348382689974e2, 1.037878290717089587658e3,
2.492228976241877759138e3, 6.071406374098611507965e3,
1.495953266639752885229e4, 3.719768849068903560439e4,
9.319251363396537129882e4, 2.349558524907683035782e5,
5.955609986708370018502e5, 1.516637894042516884433e6,
3.877904330597443502996e6, 9.950907251046844760026e6,
2.561565266405658882048e7, 6.612718635548492136250e7,
1.711446713003636684975e8, 4.439663698302712208698e8,
1.154115391849182948287e9, 3.005950906525548689841e9,
7.842940991898186370453e9, 2.049649711988081236484e10,
5.364511859231469415605e10, 1.405991957584069047340e11,
3.689732094072741970640e11, 9.694555759683939661662e11,
2.550043566357786926147e12, 6.714640184076497558707e12,
1.769803724411626854310e13, 4.669055014466159544500e13,
1.232852079912097685431e14, 3.257988998672263996790e14,
8.616388199965786544948e14, 2.280446200301902595341e15,
6.039718263611241578359e15, 1.600664914324504111070e16,
4.244796092136850759368e16, 1.126348290166966760275e17,
2.990444718632336675058e17, 7.943916035704453771510e17,
2.111342388647824195000e18, 5.614329680810343111535e18,
1.493630213112993142255e19, 3.975442747903744836007e19,
1.058563689713169096306e20 };
private static double expl(final double x)
{
return Math.exp(x);
}
private static double fabsl(final double x)
{
return Math.abs(x);
}
private static double logl(final double x)
{
return Math.log(x);
}
// //////////////////////////////////////////////////////////////////////////////
// static double Argument_Addition_Series_Ei(double x) //
// //
// Description: //
// For 6.8 < x < 50.0, the argument addition series is used to calculate //
// Ei. //
// //
// The argument addition series for Ei(x) is: //
// Ei(x+dx) = Ei(x) + exp(x) Sum j! [exp(j) expj(-dx) - 1] / x^(j+1), //
// where the Sum extends from j = 0 to inf, |x| > |dx| and expj(y) is //
// the exponential polynomial expj(y) = Sum y^k / k!, the Sum extending //
// from k = 0 to k = j. //
// //
// Arguments: //
// double x //
// The argument of the exponential integral Ei(). //
// //
// Return Value: //
// The value of the exponential integral Ei evaluated at x. //
// //////////////////////////////////////////////////////////////////////////////
private static double Argument_Addition_Series_Ei(final double x)
{
final int k = (int) (x + 0.5);
int j = 0;
final double xx = k;
final double dx = x - xx;
double xxj = xx;
final double edx = expl(dx);
double Sm = 1.0;
double Sn = (edx - 1.0) / xxj;
double term = DBL_MAX;
double factorial = 1.0;
double dxj = 1.0;
while (fabsl(term) > epsilon * fabsl(Sn))
{
j++;
factorial *= j;
xxj *= xx;
dxj *= (-dx);
Sm += (dxj / factorial);
term = (factorial * (edx * Sm - 1.0)) / xxj;
Sn += term;
}
return ei[k - 7] + Sn * expl(xx);
}
}

Java Error 'error: cannot find symbol'

I am in the process of learning Java. Below is the program that I've been trying to compile, but cannot figure out why 'x' in line 38 provides the following error: 'cannot find symbol'. Any help would be greatly appreciated.
import java.util.Scanner;
class metropolis_HW2_7 {
static int count = 0;
public static void main(String[] args) {
double a = 0.;
double b = Math.PI;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println(" Number of bins?");
int nbin = sc.nextInt();
if (nbin < 1)
System.exit(0);
double[] bin = new double[nbin];
System.out.println(" Number of histories to run?");
int N = sc.nextInt();
double dx = (b - a) / nbin;
for (int i = 0; i < N; i++) {
if (count == 0) {
double squiggle1 = Math.PI * Math.random();
double squiggle2 = Math.PI * Math.random();
double y_1 = 2 * squiggle1 + Math.sin(squiggle1);
double y_2 = 2 * squiggle2 + Math.sin(squiggle2);
if (y_2 < y_1) {
squiggle1 = squiggle2;
double x = squiggle2;
} else {
squiggle1 = squiggle1;
double x = squiggle2 / squiggle1;
}
count++;
} else {
double squiggle1;
double x = Sample(squiggle1);
}
int binNumber = (int) ((x - a) / dx);
bin[binNumber] += 1.;
}
double x = a - dx / 2.;
for (int i = 0; i < nbin; i++) {
x += dx;
bin[i] /= N * dx;
System.out.printf(" Bin %1$5d Sample for x = %2$7.5f is %3$7.5f vs %4$7.5f Ratio (%5$f) \n", i, x, bin[i], PDF(x), bin[i] / PDF(x));
}
}
}
static double Sample(double squiggle1) {
double squiggle2 = Math.PI * Math.random();
double y_1 = 2 * squiggle1 + Math.sin(squiggle1);
double y_2 = 2 * squiggle2 + Math.sin(squiggle2);
if (y_2 < y_1) {
squiggle1 = squiggle2;
return squiggle2;
} else {
squiggle1 = squiggle1;
return squiggle2 / squiggle1;
}
count++;
}
static double PDF(double x) {
return (2 * x + Math.sin(x)) / (Math.pow(Math.PI, 2) + 2);
}
}
Variables only exist inside the scope (between { and }) they're declared in. You have three different variables called x, and none of them exist when the line int binNumber=(int)((x-a)/dx); is executed.
Declare a variable outside the if statements, and then assign it inside it, something like this: (I've removed most of your code to make this example clearer; obvious you still need it)
double x;
if (count==0) {
if (y_2<y_1) {
x=squiggle2;
} else {
x=squiggle2/squiggle1;
}
} else {
x=Sample(squiggle1);
}
int binNumber=(int)((x-a)/dx);
Declare double x variable globally.You are declared in else part thats why it could not find the variable.
Scope variable Example:
int a = 80; // Create a global variable "a"
void setup() {
size(640, 360);
background(0);
stroke(255);
noLoop();
}
void draw() {
// Draw a line using the global variable "a"
line(a, 0, a, height);
// Create a new variable "a" local to the for() statement
for (int a = 120; a < 200; a += 2) {
line(a, 0, a, height);
}
// Create a new variable "a" local to the draw() function
int a = 300;
// Draw a line using the new local variable "a"
line(a, 0, a, height);
// Make a call to the custom function drawAnotherLine()
drawAnotherLine();
// Make a call to the custom function setYetAnotherLine()
drawYetAnotherLine();
}
void drawAnotherLine() {
// Create a new variable "a" local to this method
int a = 320;
// Draw a line using the local variable "a"
line(a, 0, a, height);
}
void drawYetAnotherLine() {
// Because no new local variable "a" is set,
// this line draws using the original global
// variable "a", which is set to the value 80.
line(a+2, 0, a+2, height);
}
The variable x is not declared in the scope in which it is used at that line. You are defining and assigning the double x inside two different if-blocks. Try declaring the variable in a broader scope (say, before the if-block, then assign it locally. Then it will be accessible in all 3 places.
Here's a simple example to explain what I mean:
void method()
{
if (2 > 1)
double x = 2;
else
double x = 3;
System.out.println(x); //ERROR, because x is out of scope
}
So change it to
void method()
{
double x = 0;
if (2 > 1)
x = 2;
else
x = 3;
System.out.println(x); //No error; x is referenced in the same scope in which it is declared
}

Problems updating labels using variables from if-statements (Java)

First of all, I´m new to both Java and programming (except Matlab), so simple answers is much appreciated :-).
I'm trying to create a temperature converter (with GUI) and I need to update some labels. That worked fine in the beginning, but now I have to use values from inside an if-statement. This results in an error where I try to update the labels:
tempKelvin cannot be resolved to a variable
All the action happens when the "Convert" button is clicked, the code for this is here:
// Create and add convert button
JButton fahrenheitButton = new JButton("Convert");
fahrenheitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Check if input is of type double and perform action
if (isNumber(tempTextField.getText())) {
double inputTemp = Double.parseDouble(tempTextField.getText());
// Convert from Kelvin
if (((String) unitDropdown.getSelectedItem()).equals("Kelvin")) {
int tempKelvin = (int) (inputTemp);
int tempCelcius = (int) (inputTemp - 273.15);
int tempFahrenheit = (int) ((inputTemp - 273.15) * (9/5) + 32);
// Convert from Celsius
} else if (((String) unitDropdown.getSelectedItem()).equals("Celsius")) {
int tempKelvin = (int) (inputTemp + 273.15);
int tempCelcius = (int) (inputTemp);
int tempFahrenheit = (int) (inputTemp * (9/5) + 32);
// Convert from Fahrenheit
} else if (((String) unitDropdown.getSelectedItem()).equals("Fahrenheit")) {
int tempKelvin = (int) ((inputTemp - 32) * (5/9) + 273.15);
int tempCelcius = (int) ((inputTemp - 32) * (5/9));
int tempFahrenheit = (int) ((inputTemp - 273.15) * (9/5) + 32);
// If none of the above was selected, it's an error...
} else {
int tempKelvin = 0;
int tempCelcius = 0;
int tempFahrenheit = 0;
warningLabel.setText("Oops, this doesn't look good!");
}
// Update labels
kelvinLabel.setText(tempKelvin + " K");
celsiusLabel.setText(tempCelcius + " C");
fahrenheitLabel.setText(tempFahrenheit + " F");
warningLabel.setText("");
} else {
warningLabel.setText("Input must be numeric!");
}
}
});
fahrenheitButton.setBounds(20, 45, 89, 23);
contentPane.add(fahrenheitButton);
Any help would be greatly appreciated, thanks!!
YOu need to define int tempKelvin outside the if statements and reuse it as mentioned here:
// Create and add convert button
JButton fahrenheitButton = new JButton("Convert");
fahrenheitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Check if input is of type double and perform action
if (isNumber(tempTextField.getText())) {
double inputTemp = Double.parseDouble(tempTextField.getText());
int tempKelvin = -1;
int tempCelcius = -1;
int tempFahrenheit = -1;
// Convert from Kelvin
if (((String) unitDropdown.getSelectedItem()).equals("Kelvin")) {
tempKelvin = (int) (inputTemp);
tempCelcius = (int) (inputTemp - 273.15);
tempFahrenheit = (int) ((inputTemp - 273.15) * (9/5) + 32);
// Convert from Celsius
} else if (((String) unitDropdown.getSelectedItem()).equals("Celsius")) {
tempKelvin = (int) (inputTemp + 273.15);
tempCelcius = (int) (inputTemp);
tempFahrenheit = (int) (inputTemp * (9/5) + 32);
// Convert from Fahrenheit
} else if (((String) unitDropdown.getSelectedItem()).equals("Fahrenheit")) {
tempKelvin = (int) ((inputTemp - 32) * (5/9) + 273.15);
tempCelcius = (int) ((inputTemp - 32) * (5/9));
tempFahrenheit = (int) ((inputTemp - 273.15) * (9/5) + 32);
// If none of the above was selected, it's an error...
} else {
tempKelvin = 0;
tempCelcius = 0;
tempFahrenheit = 0;
warningLabel.setText("Oops, this doesn't look good!");
}
// Update labels
kelvinLabel.setText(tempKelvin + " K");
celsiusLabel.setText(tempCelcius + " C");
fahrenheitLabel.setText(tempFahrenheit + " F");
warningLabel.setText("");
} else {
warningLabel.setText("Input must be numeric!");
}
}
});
fahrenheitButton.setBounds(20, 45, 89, 23);
contentPane.add(fahrenheitButton);
Your problem is you create a new temp variable in every if [else] statement. That's why the variable doesn't exist outside these statement(s).
You're referencing the "temp" variables out of their scope.
They are declared in each statement of your if/else conditional statement, but referenced after the conditional statement is closed (under comment "update labels").
One solution is to declare your variables before the conditional statement and only assign them in the conditions.
Your magic word is: Scope.
Because your variable is defined inside your if-statement, it actually 'dissapears' after that statement ('scope' if you will) - ends.
Just extract your variable to the most-outer scope you want to refer to it in. Good luck!
You better do this:
int tempKelvin = 0;
int tempCelcius = 0;
int tempFahrenheit = 0;
if(condition1){
///
}else if(condition2){
//
}else if(condition3){
//
}else{
//
}
inside if, you don't need to re-declare int function, just tempKelvin=....;

Strange issue in converting Feet and Inches to Centimeter and Vice Versa

public static double convertFeetandInchesToCentimeter(String feet, String inches) {
double heightInFeet = 0;
double heightInInches = 0;
try {
if (feet != null && feet.trim().length() != 0) {
heightInFeet = Double.parseDouble(feet);
}
if (inches != null && inches.trim().length() != 0) {
heightInInches = Double.parseDouble(inches);
}
} catch (NumberFormatException nfe) {
}
return (heightInFeet * 30.48) + (heightInInches * 2.54);
}
Above is the function for converting Feet and Inches to Centimeter.Below is the function for converting Centimeter back to Feet and Inches.
public static String convertCentimeterToHeight(double d) {
int feetPart = 0;
int inchesPart = 0;
if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {
feetPart = (int) Math.floor((d / 2.54) / 12);
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
}
return String.format("%d' %d''", feetPart, inchesPart);
}
I have a problem when i enter normal values like 5 Feet and 6 Inches, its converting perfectly to centimeter and again it gets converted back to 5 Feet and 6 Inches.
The Problem is when i convert 1 Feet and 1 inches or 2 Feet and 2
inches, its getting converted back to 1 Feet 2 inches and 2 Feet 3
inches.
I ran the following code
public class FeetInches{
public static void main(String[] args){
double d = convertFeetandInchesToCentimeter("1","1");
String back_again = convertCentimeterToHeight(d);
System.out.println(back_again);
}
public static double convertFeetandInchesToCentimeter(String feet, String inches) {
double heightInFeet = 0;
double heightInInches = 0;
try {
if (feet != null && feet.trim().length() != 0) {
heightInFeet = Double.parseDouble(feet);
}
if (inches != null && inches.trim().length() != 0) {
heightInInches = Double.parseDouble(inches);
}
} catch (NumberFormatException nfe) {
}
return (heightInFeet * 30.48) + (heightInInches * 2.54);
}
public static String convertCentimeterToHeight(double d) {
int feetPart = 0;
int inchesPart = 0;
if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {
feetPart = (int) Math.floor((d / 2.54) / 12);
System.out.println((d / 2.54) - (feetPart * 12));
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
}
return String.format("%d' %d''", feetPart, inchesPart);
}
}
And got
1.0000000000000018
1' 2''
By using the ceiling function you are rounding up to 2 when you really want to be rounding down to 1.
I believe:
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
Should be:
inchesPart = (int) Math.floor((d / 2.54) - (feetPart * 12));
The problem is because of the way java handles floating point numbers.
inchesPart = (int) Math.ceil(Math.round((d / 2.54) - (feetPart * 12)));
or
inchesPart = (int) Math.floor((d / 2.54) - (feetPart * 12));
In case of input 2,2 the original value of inchesPart is 2.0000000000000036 -> ceil ->3
The main issue with you're code is that you're not using the same rounding function for each part :
int feetPart = (int) Math.floor((d / 2.54) / 12);
^^^^^
int inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
^^^^
You should also do the rounding before the decomposition in order to obtain consistent results :
int feetPart = ((int) Math.round(d / 2.54)) / 12;
int inchesPart = ((int) Math.round((d / 2.54)) - (feetPart * 12);
Which could be factorized to:
int inches = (int) Math.round(d / 2.54);
int feetPart = inches / 12;
int inchesPart = inches - (feetPart * 12);
Or since ( inches - ( ( inches / 12 ) * 12) ) == ( inches % 12 ):
int inches = (int) Math.round(d / 2.54);
feetPart = inches / 12;
inchesPart = inches % 12;
You can interchange Math.round with Math.floor or Math.ceil depending on the result you expect.
I know this is old may be useful for someone else (Kotlin version)
fun feetToCentimeter(feetval: String): String {
var heightInFeet = 0.0
var heightInInches = 0.0
var feet = ""
var inches = ""
if (!TextUtils.isEmpty(feetval)) {
if (feetval.contains("'")) {
feet = feetval.substring(0, feetval.indexOf("'"))
}
if (feetval.contains("\"")) {
inches = feetval.substring(feetval.indexOf("'") + 1, feetval.indexOf("\""))
}
}
try {
if (feet.trim { it <= ' ' }.isNotEmpty()) {
heightInFeet = feet.toDouble()
}
if (inches.trim { it <= ' ' }.isNotEmpty()) {
heightInInches = inches.toDouble()
}
} catch (nfe: NumberFormatException) {
}
return (((heightInFeet * 12.0) + heightInInches) * 2.54).toString()
}
fun centimeterToFeet(centemeter: String?): String {
var feetPart = 0
var inchesPart = 0
if (!TextUtils.isEmpty(centemeter)) {
val dCentimeter = java.lang.Double.valueOf(centemeter!!)
feetPart = Math.floor((dCentimeter / 2.54) / 12).toInt()
println(dCentimeter / 2.54 - feetPart * 12)
inchesPart = Math.floor((dCentimeter / 2.54) - (feetPart * 12)).toInt()
}
return String.format("%d' %d\"", feetPart, inchesPart)
}

XOR Neural Network in Java

I'm trying to implement and train a five neuron neural network with back propagation for the XOR function in Java. My code (please excuse it's hideousness):
public class XORBackProp {
private static final int MAX_EPOCHS = 500;
//weights
private static double w13, w23, w14, w24, w35, w45;
private static double theta3, theta4, theta5;
//neuron outputs
private static double gamma3, gamma4, gamma5;
//neuron error gradients
private static double delta3, delta4, delta5;
//weight corrections
private static double dw13, dw14, dw23, dw24, dw35, dw45, dt3, dt4, dt5;
//learning rate
private static double alpha = 0.1;
private static double error;
private static double sumSqrError;
private static int epochs = 0;
private static boolean loop = true;
private static double sigmoid(double exponent)
{
return (1.0/(1 + Math.pow(Math.E, (-1) * exponent)));
}
private static void activateNeuron(int x1, int x2, int gd5)
{
gamma3 = sigmoid(x1*w13 + x2*w23 - theta3);
gamma4 = sigmoid(x1*w14 + x2*w24 - theta4);
gamma5 = sigmoid(gamma3*w35 + gamma4*w45 - theta5);
error = gd5 - gamma5;
weightTraining(x1, x2);
}
private static void weightTraining(int x1, int x2)
{
delta5 = gamma5 * (1 - gamma5) * error;
dw35 = alpha * gamma3 * delta5;
dw45 = alpha * gamma4 * delta5;
dt5 = alpha * (-1) * delta5;
delta3 = gamma3 * (1 - gamma3) * delta5 * w35;
delta4 = gamma4 * (1 - gamma4) * delta5 * w45;
dw13 = alpha * x1 * delta3;
dw23 = alpha * x2 * delta3;
dt3 = alpha * (-1) * delta3;
dw14 = alpha * x1 * delta4;
dw24 = alpha * x2 * delta4;
dt4 = alpha * (-1) * delta4;
w13 = w13 + dw13;
w14 = w14 + dw14;
w23 = w23 + dw23;
w24 = w24 + dw24;
w35 = w35 + dw35;
w45 = w45 + dw45;
theta3 = theta3 + dt3;
theta4 = theta4 + dt4;
theta5 = theta5 + dt5;
}
public static void main(String[] args)
{
w13 = 0.5;
w14 = 0.9;
w23 = 0.4;
w24 = 1.0;
w35 = -1.2;
w45 = 1.1;
theta3 = 0.8;
theta4 = -0.1;
theta5 = 0.3;
System.out.println("XOR Neural Network");
while(loop)
{
activateNeuron(1,1,0);
sumSqrError = error * error;
activateNeuron(0,1,1);
sumSqrError += error * error;
activateNeuron(1,0,1);
sumSqrError += error * error;
activateNeuron(0,0,0);
sumSqrError += error * error;
epochs++;
if(epochs >= MAX_EPOCHS)
{
System.out.println("Learning will take more than " + MAX_EPOCHS + " epochs, so program has terminated.");
System.exit(0);
}
System.out.println(epochs + " " + sumSqrError);
if (sumSqrError < 0.001)
{
loop = false;
}
}
}
}
If it helps any, here's a diagram of the network.
The initial values for all the weights and the learning rate are taken straight from an example in my textbook. The goal is to train the network until the sum of the squared errors is less than .001. The textbook also gives the values of all the weights after the first iteration (1,1,0) and I've tested my code and its results match the textbook's results perfectly. But according to the book, this should only take 224 epochs to converge. But when I run it, it always reaches MAX_EPOCHS unless it is set to several thousand. What am I doing wrong?
//Add this in the constants declaration section.
private static double alpha = 3.8, g34 = 0.13, g5 = 0.21;
// Add this in activate neuron
gamma3 = sigmoid(x1 * w13 + x2 * w23 - theta3);
gamma4 = sigmoid(x1 * w14 + x2 * w24 - theta4);
if (gamma3 > 1 - g34 ) {gamma3 = 1;}
if (gamma3 < g34) {gamma3 = 0;}
if (gamma4 > 1- g34) {gamma4 = 1;}
if (gamma4 < g34) {gamma4 = 0;}
gamma5 = sigmoid(gamma3 * w35 + gamma4 * w45 - theta5);
if (gamma5 > 1 - g5) {gamma5 = 1;}
if (gamma5 < g5) {gamma5 = 0;}
ANN should learn in 66 iterations, but is on the brink of divergence.
Try making rounding of gamma3, gamma4, gamma5 while in activation phase for instace:
if (gamma3 > 0.7) gamma3 = 1;
if (gamma3 < 0.3) gamma3 = 0;
and rise little bit learnig variable ( alpha )
alpha = 0.2;
learning ends in 466 epochs.
Of course if u make bigger rounding and higher alpha u set u can achieve even better result than 224.
Whole point of this network is to show how to deal with a situation when grouping isn't based on "top = yes, bottom = no", but rather there is a central line (going through points (0,1) and (1,0) in this case) and if value is close to the line, then answer is "yes", while if it is far, then answer is "no". You can't cluster such system with just one layer. However two layers is enough.

Categories