The following code is designed to factorize a number typed into the variable x.
public class testMod{
public static void main(String[]args){
double x = 11868681080091051216000;
StringBuilder output = new StringBuilder("1 * ");
for(double y = 2; y <= x; y++){
while (x % y == 0) {
System.out.print("Calculating... \n");
String printNumber = y + " * ";
x = x / y;
output.append(printNumber);
System.out.print(output.substring(0, output.length() - 2) + "\n");
}
}
}
}
The problem is that the compiler treats 11868681080091051216000 as an int, regardless of the attempt to assign it to a double. As such, it's out of range.
To specify a double literal, you can simply append D to the end – but do note that you'll lose precision this way:
double x = 11868681080091051216000D;
System.out.println(x); // prints 186868108009105E22
If you need the full precision, you can use a BigInteger instead, but you'll still need to specify that number in expressions that Java can handle, such as a product of its factors.
Related
What is wrong with this code? It says cannot convert from String to int, but I have already converted it.
public static void main(String[] args) {
String x = JOptionPane.showInputDialog(null, "Hur många värden haver du?");
int i = Integer.parseInt(x);
for (int y = 0; i >= y; y++) {
String z = JOptionPane.showInputDialog(null, "Skriv in värdet");
int sum = Integer.parseInt(z);
sum = (sum + z);
}
}
No you have converted z to int and store the result in sum so sum is the int value of z but z is still a variable of type String. What you are trying to do here is the same as multiplying sum by two.
But i assum you want to sum all input values, so you can do sum = (sum + Integer.parseInt(z)); and put the declaration of sum outside the loop, otherwise you initialize it on every iteration. Another bug is that if you input x it will iterate x + 1 times because of i >= y. Fixed version below.
String x = JOptionPane.showInputDialog(null, "Hur många värden haver du?");
int i = Integer.parseInt(x);
int sum = 0;
for (int y = 0; i > y; y++)
{
String z = JOptionPane.showInputDialog(null, "Skriv in värdet");
sum = (sum + Integer.parseInt(z));
}
System.out.println(sum);
Input: 3 (number of iterations)
Input: 7
Input: 5
Input: 6
Output: 18
Java don't do automatic conversion between types. So you can't add Strings with numbers and expect it to do math.
What Java does do it auto boxing of primitive types to objects. And it will automatically attempt to call toString() on objects if you use it in a String concatenation.
So as Reimeus wrote. You need to convert the String to a number before you start using it in math
Cannot convert from String to int
sum=(sum+z) // int+string // this was the problem
change your z to int as:
int iz= Integer.parseInt(z);
sum = (sum + iz);
int sum = 0;
for (int y = 0; i >= y; y++) {
try{
String z = JOptionPane.showInputDialog(null, "Skriv in värdet");
sum = (sum + Integer.parseInt(z));
} catch (Exception e){
System.out.println("This was not an Integer: " + z);
}
}
The exception will prevent your program from crashing, but it will not screw up your 'sum'. So you can put an other value again, and go on...
I am looking to write a method in Java which finds a derivative for a continuous function. These are some assumptions which have been made for the method -
The function is continuous from x = 0 to x = infinity.
The derivative exists at every interval.
A step size needs to be defined as a parameter.
The method will find the max/min for the continuous function over a given interval [a:b].
As an example, the function cos(x) can be shown to have maximum or minimums at 0, pi, 2pi, 3pi, ... npi.
I am looking to write a method that will find all of these maximums or minimums provided a function, lowerBound, upperBound, and step size are given.
To simplify my test code, I wrote a program for cos(x). The function I am using is very similar to cos(x) (at least graphically). Here is some Test code that I wrote -
public class Test {
public static void main(String[] args){
Function cos = new Function ()
{
public double f(double x) {
return Math.cos(x);
}
};
findDerivative(cos, 1, 100, 0.01);
}
// Needed as a reference for the interpolation function.
public static interface Function {
public double f(double x);
}
private static int sign(double x) {
if (x < 0.0)
return -1;
else if (x > 0.0)
return 1;
else
return 0;
}
// Finds the roots of the specified function passed in with a lower bound,
// upper bound, and step size.
public static void findRoots(Function f, double lowerBound,
double upperBound, double step) {
double x = lowerBound, next_x = x;
double y = f.f(x), next_y = y;
int s = sign(y), next_s = s;
for (x = lowerBound; x <= upperBound ; x += step) {
s = sign(y = f.f(x));
if (s == 0) {
System.out.println(x);
} else if (s != next_s) {
double dx = x - next_x;
double dy = y - next_y;
double cx = x - dx * (y / dy);
System.out.println(cx);
}
next_x = x; next_y = y; next_s = s;
}
}
public static void findDerivative(Function f, double lowerBound, double
upperBound, double step) {
double x = lowerBound, next_x = x;
double dy = (f.f(x+step) - f.f(x)) / step;
for (x = lowerBound; x <= upperBound; x += step) {
double dx = x - next_x;
dy = (f.f(x+step) - f.f(x)) / step;
if (dy < 0.01 && dy > -0.01) {
System.out.println("The x value is " + x + ". The value of the "
+ "derivative is "+ dy);
}
next_x = x;
}
}
}
The method for finding roots is used for finding zeroes (this definitely works). I only included it inside my test program because I thought that I could somehow use similar logic inside the method which finds derivatives.
The method for
public static void findDerivative(Function f, double lowerBound, double
upperBound, double step) {
double x = lowerBound, next_x = x;
double dy = (f.f(x+step) - f.f(x)) / step;
for (x = lowerBound; x <= upperBound; x += step) {
double dx = x - next_x;
dy = (f.f(x+step) - f.f(x)) / step;
if (dy < 0.01 && dy > -0.01) {
System.out.println("The x value is " + x + ". The value of the "
+ "derivative is "+ dy);
}
next_x = x;
}
}
could definitely be improved. How could I write this differently? Here is sample output.
The x value is 3.129999999999977. The value of the derivative is -0.006592578364594814
The x value is 3.1399999999999766. The value of the derivative is 0.0034073256197308943
The x value is 6.26999999999991. The value of the derivative is 0.008185181673381337
The x value is 6.27999999999991. The value of the derivative is -0.0018146842631128202
The x value is 9.409999999999844. The value of the derivative is -0.009777764220086915
The x value is 9.419999999999844. The value of the derivative is 2.2203830347677922E-4
The x value is 12.559999999999777. The value of the derivative is 0.0013706082193754021
The x value is 12.569999999999776. The value of the derivative is -0.00862924258597797
The x value is 15.69999999999971. The value of the derivative is -0.002963251265619693
The x value is 15.70999999999971. The value of the derivative is 0.007036644660118885
The x value is 18.840000000000146. The value of the derivative is 0.004555886794943564
The x value is 18.850000000000147. The value of the derivative is -0.005444028885981389
The x value is 21.980000000000636. The value of the derivative is -0.006148510767989279
The x value is 21.990000000000638. The value of the derivative is 0.0038513993028788107
The x value is 25.120000000001127. The value of the derivative is 0.0077411191450771355
The x value is 25.13000000000113. The value of the derivative is -0.0022587599505241585
The main thing that I can see to improve performance in the case that f is expensive to compute, you could save the previous value of f(x) instead of computing it twice for each iteration. Also dx is never used and would always be equal to step anyway. next_x also never used. Some variable can be declare inside the loop. Moving the variable declarations inside improves readability but not performance.
public static void findDerivative(Function f, double lowerBound, double upperBound, double step) {
double fxstep = f.f(x);
for (double x = lowerBound; x <= upperBound; x += step) {
double fx = fxstep;
fxstep = f.f(x+step);
double dy = (fxstep - fx) / step;
if (dy < 0.01 && dy > -0.01) {
System.out.println("The x value is " + x + ". The value of the "
+ "derivative is " + dy);
}
}
}
The java code you based on (from rosettacode) is not OK, do not depend on it.
it's expecting y (a double value) will become exactly zero.
You need a tolerance value for such kind of tests.
it's calculating derivative, and using Newton's Method to calculate next x value,
but not using it to update x, there is not any optimization there.
Here there is an example of Newton's Method in Java
Yes you can optimize your code using Newton's method,
Since it can solve f(x) = 0 when f'(x) given,
also can solve f'(x) = 0 when f''(x) given, same thing.
To clarify my comment, I modified the code in the link.
I used step = 2, and got correct results.
Check how fast it's, compared to other.
That's why optimization is used,
otherwise reducing the step size and using brute force would do the job.
class Test {
static double f(double x) {
return Math.sin(x);
}
static double fprime(double x) {
return Math.cos(x);
}
public static void main(String argv[]) {
double tolerance = .000000001; // Our approximation of zero
int max_count = 200; // Maximum number of Newton's method iterations
/*
* x is our current guess. If no command line guess is given, we take 0
* as our starting point.
*/
double x = 0.6;
double low = -4;
double high = 4;
double step = 2;
int inner_count = 0;
for (double initial = low; initial <= high; initial += step) {
x = initial;
for (int count = 1; (Math.abs(f(x)) > tolerance)
&& (count < max_count); count++) {
inner_count++;
x = x - f(x) / fprime(x);
}
if (Math.abs(f(x)) <= tolerance) {
System.out.println("Step: " + inner_count + ", x = " + x);
} else {
System.out.println("Failed to find a zero");
}
}
}
}
Have a look at this code
Integer x = 5;
Integer y = 2;
Integer xy = x+y;
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7
x++;
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7
How can I get the code to output 8 without using a method that calculates it for you?
An Integer in Java is immutable. You can not change its value. In addition, it's a special autoboxing type to provide an Object wrapper for the int primitive.
In your code, for example, x++ does not modify the Integer object x is referencing. It un-autoboxes it to a primitive int, post-increments it, re-autoboxes it returning a new Integer object and assigns that Integer to x.
Edit to add for completeness: Autoboxing is one of those special things in Java that can cause confusion. There's even more going on behind the scenes when talking about memory / objects. The Integer type also implements the flyweight pattern when autoboxing. Values from -128 to 127 are cached. You should always use the .equals() method when comparing Integer objects.
Integer x = 5;
Integer y = 5;
if (x == y) // == compares the *reference (pointer) value* not the contained int value
{
System.out.println("They point to the same object");
}
x = 500;
y = 500;
if (x != y)
{
System.out.println("They don't point to the same object");
if (x.equals(y)) // Compares the contained int value
{
System.out.println("But they have the same value!");
}
}
See: Why aren't Integers cached in Java? for more info (and of course the JLS)
You need to update xy after modifying x. So:
x++;
xy = x + y;
xy2 = x + y;
In Java you'll need to update a variable yourself if you want the value to change. It's not like other languages where you express a relationship between two variables and this relationship is maintained whenever a variable changes.
The expression:
xy = x + y
doesn't mean that now xy is depends on the values of x and y (if they changed, xy is changed too). You can see it as follows: the value of the expression x + y is inserted into xy.
Therefore, you must increase the value of x (by x++), before your set the value of xy.
I'm new to java, and I'm not really sure of the context for this question, but if all you want to do is output 8, you can just make it xy++ instead of x++.
Integer x = 5;
Integer y = 2;
Integer xy = x+y;
int xy2 = x+y; // just testing to see if it makes a difference
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7
**xy++;**
System.out.println("xy = " + xy); // **outputs: 8**
System.out.println("xy2 = " + xy2); // outputs: 7
I have some lines of code that produces a number after calculation which is currently in JavaScript and here is the code:
if ( y2 != y1 )
{
// calculate rate
var f;
var y;
if ( y2 > y1 )
{
f = cpi[y2] / cpi[y1];
y = y2 - y1;
}
else
{
f = cpi[y1] / cpi[y2];
y = y1 - y2;
}
var r = Math.pow(f, 1/y);
r = (r-1)*100;
r = Math.round(r*100) / 100;
System.out.println( "number: " + r.toFixed(2) + "%." );
}
I converted the above JS code to Java and here is the code:
DecimalFormat decimalFormat = new DecimalFormat("0.##");
if (cpi[to] != cpi[from]) {
double f, y;
if (cpi[to] > cpi[from]) {
f = cpi[to] / cpi [from];
y = to - from;
}
else {
f = cpi[from] / cpi[to];
y = from - to;
}
q = Math.pow(f, 1/y);
q = (q-1)*100;
q = Math.round(q*100)/100;
Toast.makeText(getApplicationContext(), "number: " + String.valueOf(decimalFormat.format(q)), 2000).show();
}
The JavaScript code produces: number: 2.39
While the Java code produces number: 2
Why am I getting two different value? I will post what cpi[to], cpi[from], to and from values are if needed.
In this line
q = Math.round(q*100)/100;
both operands of the division operation are integral, therefore the result is also an integral type. Use 100.0 as the divisor to coerce the result to a double.
what is q type?
try to put 100.0 also
If you devide two integers in java the result is integer. Every operation with double and integer or with two doubles creates double.
1)In this line
1)q = Math.round(q*100)/100;
2)you are deviding two integers, so it has same output as:
2)q = (int) (Math.round(q*100)/100);
3)you can use casting to double for example:
3)q = Math.round(q*100)/(double)100;
4)or using the 100.0 which makes this number double:
4)q = Math.round(q*100)/100.0;
5)this should work too, because first the result of Math.round is converted to double and then devided by 100:
5)q = (double)Math.round(q*100)/100;
6)However this WILL NOT work, because first Math.round is devided by 100 and it creates integer, so the result of this operation is rounded down and AFTER then casted to double. So it will be double but still rounded down, because it was rounded before it becomes double.
6)q = (double)(Math.round(q*100)/100);
Most likely your issue is Math.round(double) returns a long value. So d would contain a long instead of a double at that point.
The code that I have,
public static void main(String[] args) {
int x = 27;
int y = 5;
double z = x / y;
System.out.println(" x = " + x + " y = "+y +" z = "+z);
}
In the above code I know that to print out the decimal place .4 for the variable z we have to use printf, but my question is why does the variable z is not storing the 5.4 and just storing 5?
I mean int / int then the out put is stored in a double, which is perfectly capable of holding decimal values but it is not, what is the logic?
This is happening because the values that you are dividing with are int and not double and they are not going to output the decimal places, to be more clear take this for example
double z = 27 /5;
same as yours
double z = 27.0/5.0;
now z = 5.4;
So this shows that the datatype that you are performing calculation with also should be the same as the datatype you are expecting the output to be.
You need to cast one of the operands to a double
double z = (double) x / y;
The reason is x / y stand-alone is an int, so it is really evaluating as 5 and then parsing to a double.
You have to cast the integers before you divide I believe.
Like this,
double z = (double) x / (double) y;
What you're doing in the line:
double z = x / y;
is integer division, and then you convert the outcome to double