Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is it possible to change the meaning of the asterisk symbol (multiplication operator) in Java?
I want to do this:
int ex = 600 * 0.98;
It fails because you can't convert from double to int. Can I make it so that I'm able to convert the double to an integer? Or does the
asterisk only have one meaning that can't be changed?
I just want the OPERATION in math, not a string.
To have an operation, you must have code. One way of doing this is to have a method like
public static double ex(double factor) {
return factor * 0.98;
}
or if the factor is a field
private double factor = 600;
public double ex() {
return factor * 98 / 100;
}
public static void main(String... ignored) {
Main m = new Main();
System.out.println("factor: "+m.factor+" ex: "+ m.ex());
m.factor = 700;
System.out.println("factor: "+m.factor+" ex: "+ m.ex());
}
prints
factor: 600.0 ex: 588.0
factor: 700.0 ex: 686.0
As you can see ex() is re-evaluated each time it is used.
Why do I * 98 / 100? I do this as each value can be represented exactly however 0.98 is not represent exactly and can have a small error.
System.out.println(new BigDecimal(0.98));
prints the closest representable value to 0.98
0.979999999999999982236431605997495353221893310546875
If you want to store text you need to do something like
String ex = "600 * 0.98";
An int value is for storing a whole number which is a 32-bit signed value, nothing else.
Uhhh.
The short answer is that you can't do that. A variable of type int can only store an integer value. The expression you assign to the int has to evaluate to an integer.
What integer value do you want assigned to ex?
int ex = 588; // 600 * 0.98
What meaning are you associating with the asterisk between two numeric values that is not multiplication?
If you want to store an array of characters, then:
char[] ex = "600 * 0.98".toCharArray();
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a small problem. I think it's simple, but I don't know, how to manage it properly.
I have this simple int:
int birth = 011112;
and I want output to look like this, in this specific format.
"Your birth date is 12.11.01."
I did it with an integer array, but I want only one integer input like this one, not an array.
Could some body help me? Is there any simple method to manage it of, without using loops?
Basically, the conversion of the int representing a date in some format into String should use divide / and modulo % operations, conversion to String may use String.format to provide leading 0.
The number starting with 0 is written in octal notation, where the digits in range 0-7 are used, so the literals like 010819 or 080928 cannot even be written in Java code as int because of the compilation error:
error: integer number too large
int birth = 010819;
However, (only for the purpose of this exercise) we may assume that the acceptable octal numbers start with 01 or 02 then such numbers are below 10000 decimal.
Then the numeric base for division/modulo and the type of output (%d for decimal or %o for octal) can be defined:
public static String rotate(int x) {
int base = x < 10000 ? 0100 : 100;
String type = x < 10000 ? "o" : "d";
int[] d = {
x % base,
x / base % base,
x / (base * base)
};
return String.format("%02" + type + ".%02" + type + ".%02" + type, d[0], d[1], d[2]);
}
Tests:
System.out.println(rotate(011112)); // octal
System.out.println(rotate(11112)); // decimal (no leading 0)
Output:
12.11.01
12.11.01
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this sine wave which generates floating point values (e.g. 0.37885) but I want them as shorts. Direct casting with short gives me a value of 0. so what is the solution?
Can anyone tell me how to do it - ideally without loss of precision - or minimal loss of precision if this is all that is possible?
public static short floatToShort(float x) {
if (x < Short.MIN_VALUE) {
return Short.MIN_VALUE;
}
if (x > Short.MAX_VALUE) {
return Short.MAX_VALUE;
}
return (short) Math.round(x);
}
You'll loose the fractional part:
float 4 byte floating-point
double 8 byte floating-point (normal)
short 2 byte integer
int 4 byte integer (normal)
long 8 byte integer
Edit:
Maybe you wanted to know how to save the bits of a float (4 bytes) into an int (4 bytes):
(http://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#floatToRawIntBits(float))
float x = 0.1f;
int n = Float.floatToRawIntBits(x);
float y = Float.intBitsToFloat(n);
In principle, you could just multiply it by 100000, convert it to int, then subtract -32,767 and convert it to short. If that still puts it in the -32,767 to 32,767 range for all your values, that's likely the best you can do. Otherwise, you'll have to limit your precision and multiply by 10000.
And when you use the short of course you have to remember to divide it back down.
If your input float values are in a defined range (for now let's assume they're in the range of -1..1, exclusive), you can multiply them to get a value whose fraction you'll throw away.
Valid short range is: -32768..32767 so you can multiple with 32768 in this case (max short / max input value).
For example:
float f = 0.23451f;
short s = (short) (f * 32768);
To decode a short value to float:
float f2 = s / 32768f;
short is an integral type, so it can only contain whole numbers. The only two choices for 0.37885 in a short are 0 or 1, both of which (it seems to me) lose quite a bit of precision.
So the answer is: If you're okay with losing all fractional values, either use a cast, Float#shortValue, or Math.round(float) (and cast the resulting int to short).
Example: Live Copy
float f1 = 0.37885f;
short s1 = (short)Math.round(f1);
System.out.println("s1 = " + s1);
float f2 = 27.67885f;
short s2 = (short)Math.round(f2);
System.out.println("s2 = " + s2);
Output:
s1 = 0
s2 = 28
In a comment you said:
I have this sine wave which generates values like the one mentioned above, but I want them as shorts.
Ah, now, we can do something with that. Presumably the values you're getting are all between 0 and 1. You can store them as shorts by multiplying. Since the range of a short is -32,768 to 37,767, a convenient number to multiply them by might be 10000:
short s = Math.round(floatValue * 10000);
The number we'd get for your example would be 3789. Example: Live Copy
float floatValue = 0.37885f;
short s = (short)Math.round((double)floatValue * 10000);
System.out.println("s = " + s);
That isn't the same value, of course, it's the value multipled by ten thousand, so anywhere you're going to use it, you'd have to allow for that.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to create a custom number class in java, which after ranging from 000000 to 099999 would continue with 0A0000. So the last number would be 9Z9999.
I'm a bit lost on how I could implement this in Java. I suppose I would need to create a custom class which extends Number.
My goal would be to create a class on which I could iterate through (from 000000 to 9Z9999) to reserve document ID ranges.
Although I could do achieve this end with several other workarounds, I find this to be the cleanest solution.
Thank you for any help in advance.
This seems to work. Just use an ordinary number and format it:
static String asStrangeNumber ( int i ) {
// Lowest 4 digits are decimal.
int low4 = i%10000;
i /= 10000;
// Next is base 36 - 0-9-A-Z
int c = i % 36;
i /= 36;
// Remaining should be < 10.
return String.format("%1d%c%04d", i%10, c < 10 ? '0' + c: 'A' + c - 10, low4);
}
public void test() {
test (0);
test (1);
test (10);
test (100);
test (1000);
test (10000);
test (100000);
test (1000000);
}
private void test(int i) {
System.out.println(" "+i+" -> "+asStrangeNumber(i));
}
prints
0 -> 000000
1 -> 000001
10 -> 000010
100 -> 000100
1000 -> 001000
10000 -> 010000
100000 -> 0A0000
1000000 -> 2S0000
I don't think it makes sense. Number defines methods like intValue() etc., and how can you convert 0Z0000 to int?
Just create your own CustomId class, but don't extend Number.
The simplest way to do this is to create a single class that gives out IDs (note these are not numbers per se but words). This would contain 6 counters, each of which had a maximum value (9 for 5 of them 36 for the remaining one that has numbers and letters).
When each new ID is requested the bottom counter is increased, when it reaches it's maximum value it resets to zero and increases the next counter by one etc etc. (this counter could be its own class, with fields for currentValue and maximumValue and method increment() that increments the internal value and returns a boolean as to if the higher counter should be incremented)
Then the actual ID is outputted as a String, with each counter having it's current value converted to a single character (0-9 -->'0'-'9' 10-36 --> 'A'-'Z')
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Write a program in java to divide one number by another. But these number can have any number of digits(means the numbers may be of 100,200 or more than these digits.)
If a number can be of virtually any length, use BigInteger. BigInteger provides a divide method.
Here's an example:
BigInteger a = new BigInteger("7583584848488756569");
BigInteger b = new BigInteger("-357457473437373");
BigInteger x = a.divide(b);
The java.math.BigInteger.divide(BigInteger val) returns a BigInteger whose value is (this / val).
Using BigInteger
BigInteger bi1, bi2, bi3;
bi1 = new BigInteger("-100");
bi2 = new BigInteger("3");
// divide bi1 with bi2
bi3 = bi1.divide(bi2);
String str = "Division result is " +bi3;
// print bi3 value
System.out.println( str );
The output will be
Division result is -33
A facetious answer:
For a numeric value 'x' and a numeric value 'y' there is a special operator / that when placed between these two values evaluates to a number representing the number of times the second can "fit" into the first i.e.
int x = 200;
int y = 100;
System.out.println(x / y);
will return
2
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to develop a program in Java to solve some integrals. Integrals like this:
I've looked for some functions to do this, in java.Math but I didn't find anything.
Has anyone an idea to get a solution for this? (Maybe some extra libraries or something like that).
The Wikipedia article on Numerical Integration has a section on methods for one-dimensional integrals.
You should have no problem implementing the "trapezoidal" or "rectangle" rule.
The Apache Commons Math library contains, in the Numerical Analysis section, four different numerical integrators:
Romberg's method
Simpson's method
trapezoid method
Legendre-Gauss method
Take a look at JScience
Check out Simpson's Rule on Wikipedia.
/*------------------------------------------------------------------------------------------------------
* Small program that numerically calculates an integral according to
* Simpson's algorithm. Before executing it, you must enter:
* - the expression of the function f: line 12;
* - the lower and upper limits b of the integral: lines 39 and 40;
* - the number of measurements n (n is integer !!!): line 41.
*------------------------------------------------------------------------------------------------------*/
// Class function: Defines Simpson's rule
class Function{
// Define the function to integrate
double f (double x) {
return Math.Cos(x);
}
// Simpson's method for integral calculus
// a = lower bound
// b = upper bound of integration
// n = number of passes (higher = less margin of error, but takes longer)
double IntSimpson(double a, double b,int n){
int i,z;
double h,s;
n=n+n;
s = f(a)*f(b);
h = (b-a)/n;
z = 4;
for(i = 1; i<n; i++){
s = s + z * f(a+i*h);
z = 6 - z;
}
return (s * h)/3;
}
}
class integration{
// Class result: calculates the integral and displays the result.
public static void main(String args[]){
// Call class function
Function function;
function = new Function();
// ENTER the desired values of a, b and n !!!
double a = ???? ;
double b = ???? ;
int n = ???? ;
// Applies simpson method to function
double result = function.IntSimpson(a,b,n);
// Show results
System.out.println("Integral is: " + result);
}
}