I am stuck in the scenario below:
If x is 1.5 or lower then the final result will be x = 1.
If x is large than 1.5 then x = 2.
The input number will be x/100.
For instance:
input = 0.015 => x = 1.5 => display x = 1.
The problem I got is that float number is inaccurate. For example:
input = 0.015 but actually it is something like 0.01500000000000002. In this case, x gonna be 1.500000000000002 which is large than 1.5 => display output is x = 2.
It happen so randomly which I don't know how to solve it. Like 0.5, 1.5 will give me the correct result. But 2.5, 3.5, 4.5, 5.5 will give me the wrong result. Then 6.5 will give me the correct result again.
The code I implemented is below:
float x = 0.015;
NumberFormat nf = DecimalFormat.getPercentInstance();
nf.setMaximumFractionDigits(0);
output = nf.format(x);
So depends on x, the output might be right or wrong. It is just so random.
I alos tried to use Math.round, Math.floor, Math.ceils but none of them seems work since float number is so unpredictable.
Any suggestion for the solution?
Thanks in advance.
You could use String.format.
String s = String.format("%.2f", 1.2975118);
Here is my old code golf answer.
public class Main {
public static void main(String[] args) {
System.out.println(math(1.5f));
System.out.println(math(1.500001f));
System.out.println(math(1.49999f));
}
public static int math(float f) {
int c = (int) ((f) + 0.5f);
float n = f + 0.5f;
return (n - c) % 2 == 0 ? (int) f : c;
}
}
Output:
1
2
1
I like simple answers,
Math.round(1.6); // Output:- 2
Math.round(1.5); // Output:- 2
Math.round(1.4); // Output:- 1
I was facing the same problem, I used the DecimalFormat. This might help you.
float x = 1.500000000000002f;
DecimalFormat df = new DecimalFormat("###.######");
long l = df.format(x);
System.out.println("Value of l:"+l);
Related
In Part 1 of a prompt, I am expected to integrate an equation into Java to get the value for a period (T). The equation is as follows: T = FS / (440 * (2 ^(h/12))
NOTE:
FS = sample rate, which is 44100 / 1.
h = halfstep, which is provided by the user.
An example of this equation is: 44100 / (440 * (2 ^(2/12)) = 89.3
The code I wrote is as follows:
public static double getPeriod(int halfstep) {
double T = 100; // TODO: Update this based on note
double FS = 44100 / 1;
double power = Math.pow(2, (halfstep / 12));
double denominator = 440 * (power);
double result = (FS) / (denominator);
T = Math.round(result);
return T;
}
// Equation test.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("halfstep is: ");
int halfstep = in.nextInt();
double period = getPeriod(halfstep);
System.out.print("Period: " + period + " ");
}
But when I run through this code with h = 2, T = 100.0 instead of the anticipated 89.3 and I am not sure what the issue is. Any thoughts on what's going on?
Because halfStep is an int, when you write
(halfstep / 12)
the calculation is done by taking halfStep / 12 and rounding down to the nearest integer. As a result, if you plug in 2 here, then halfStep / 12 will come back as 0 instead of 1/6. That's messing up the computation and is likely what's giving you the wrong answer.
You have a few options for how to proceed here. One would be to change halfStep to be a double rather than an int. Another would be to rewrite the division as
halfStep / 12.0
which, since 12.0 is a double literal, will perform the division in the way you intend.
One other potential issue - you declare the variable T as 100.0, but never use T anywhere in the calculation and ultimately overwrite it before returning it. I'm not sure whether this is intentional or whether that indicates that one of the formulas is incorrect.
Hope this helps!
I looked and found one post which helped me here:
Convert Linear scale to Logarithmic
However I either did some mistake I can't find or I got wrong idea of the formula. I want to convert any number from linear 1-256 range to their respective values if it was logarithmic scale. Can someone help me to correct my code? When i try values low values from zero it works kind of fine but trying to convert anything over 160 gets me result which is > 256.
Here is my code:
package linear2log;
public class Linear2Log {
public static void main(String[] args) {
System.out.println("Ats3: " + lin2log(160));
}
public static long lin2log(int z) {
int x = 1;
int y = 256;
double b = Math.log(y/x)/(y-x);
double a = 10 / Math.exp(b*10);
double tempAnswer = a * Math.exp(b*z);
long finalAnswer = Math.max(Math.round(tempAnswer) - 1, 0);
return finalAnswer;
}
}
You get the formula wrong.
For sure this line
double a = 10 / Math.exp(b*10);
You are using value 10 from example, but you should be using your value which is 256.
double a = y / Math.exp(b * y);
I don't get why are you using this line:
long finalAnswer = Math.max(Math.round(tempAnswer) - 1, 0);
This way you are always getting value that is one less than actual value.
Okay, I figured this program would be really easy. However, when the console displays the x values (shown in the system.out.), I'm getting "When x is 1.20000000000002....".
I know that 1.1 + 0.1 is not 1.200000000002, so I'm just wondering if there's a fault in my syntax or something. If you decide to run the code to see, you'll instantly see my issue.
If anyone has any suggestions, I'd greatly appreciate it!
Thank You
public class EulersMethod {
public static void main(String[] args) {
double x = 1;
double y = 1;
double h = 0.1;
while(x <= 1.4){
System.out.println("When x is " + x + ", y is " + y);
y = y + h * (- x - y);
x = x + h;
}
}
}
0.1 can not be precisely represented by a double type, so there must be some approximation/compromise to make. And for a double it is usually has only about 16 to 17 digit of significant digits. That is why you could not get 1.2 exactly.
To expand on my comment, some numbers can be written precisely in doubles, like 1/2, while others cannot.
0.5 = 1/2
so can be written exactly as a sum of powers of two
0.1 = 1/10 = 1/16 + a bit = 1/16 + 1/32 + a bit more... etc
The bit more can never be exactly a power of two, so you get the closest it can manage. It may overshoot, or undershoot.
Here's a good article on why floats are not exact (or why they should never be used in financial calculations): http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm
What you really want is BigDecimal.
Here's a short tutorial from JavaWorld: http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html
You could use the DecimalFormat to clean it up if you like.
DecimalFormat format = new DecimalFormat("0.0");
String decimalValueAsString = format.format(yourDecimalValue);
Documentation
You could also use Decimal formatting with RoundingMode and the method setRoundingMode
it´s a simple task but i´m not able to solve it on my own..
i got
double digit1 = 12.1;
double digit2 = 12.99;
and need a method which gives me this:
anyMethod(digit1); //returns 10
anyMethod(digit2); //returns 99
what i have is
public static void getAfterComma(double digit) {
BigDecimal bd = new BigDecimal(( digit - Math.floor( digit )) * 100 );
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println(bd.toBigInteger()); // prints digit1=1 and digit2=99
}
anyway i prefer integer as the returntype..
anybody got a quick solution/tip?
kindly
Why not you simply use:
int anyMethod(double a){
//if the number has two digits after the decimal point.
return (int)((a + 0.001) * 100) % 100;
}
A simple way of getting the fractional part of a double is to use the modulo operator, %. However, you'll have to take into account the fact that floating point arithmetic isn't precise. For example,
System.out.println(12.1 % 1); // outputs 0.09999999999999964
System.out.println(12.99 % 1); // outputs 0.9900000000000002
If you want to get two decimal digits as an int, which is what I think you're asking, you can achieve this, glossing over the floating point issues, like so:
System.out.println(Math.round((12.1 % 1) * 100)); // outputs 10
System.out.println(Math.round((12.99 % 1) * 100)); // outputs 99
However, you should consider going further down the BigDecimal path you started down, which uses arbitrary precision arithmetic. You could do something like this:
System.out.println(new BigDecimal("12.1").remainder(BigDecimal.ONE)); // outputs 0.1
System.out.println(new BigDecimal("12.99").remainder(BigDecimal.ONE)); // outputs 0.99
If, as before, you want two decimal digits from this, you can do this:
System.out.println(new BigDecimal("12.1").remainder(BigDecimal.ONE).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP).intValue()); // outputs 0.1
System.out.println(new BigDecimal("12.99").remainder(BigDecimal.ONE).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP).intValue()); // outputs 0.99
Note that there a couple of differences between these last two methods and the first two: they preserve the sign of the argument, so if you use the final example for -12.99, you'll get -99 back, and they treat the fractional part of an integer as 1, so if you use the final example for 12, you'll get 100 back.
It's not necessary to use Number tyeps all the time. You can take advantage of String as a mediator.
String mediator = Double.valueOf(d1).toString();
mediator = mediator.substring(mediator.indexOf('.') + 1);
Integer result = Integer.valueOf(mediator);
Try this out
public static void main(String args[]){
double a=12.99;
double b=12.1;
System.out.println(method(a));
System.out.println(method(b));
}
private static int method(double a) {
return (int) ((a*100)%100);
}
sachin-pasalkar done it! little fix but fine!
public static int anyMethod(double a){
return (int) (a*100)%100;
}
check out this code returns digits after '.' always. Without any extra parameters other than double variable.
public int anyMethod(double d)
{
String numString = d+"";
return Integer.parseInt(numString.substring(numString.indexOf('.')+1));
}
If I understand correctly, you need to return n digits after the dot for a given double number. So... let's see:
public int decimalDigits(double x, int n) {
double ans;
ans = (x - (int) x) * Math.pow(10, n);
return (int) ans;
}
Done. Hope this helps you.
For your specific example, 'n = 2' should do.
I have the following code:
float fl = ((float)20701682/(float)20991474);
And that gives me fl = 0.9861948.
I would like to convert 0.9861948 to 2% since 2% has been downloaded.
I'm downloading a file and calculating progress.
Any help would be grate.
you have constant values in the code, you should replace them with the variables representing the amount downloaded and the total size:
float downloaded = 50;
float total = 200;
float percent = (100 * downloaded) / total;
System.out.println(String.format("%.0f%%",percent));
output:
25%
I guess you mean something like
int percentage = (1 - fl) * 100;
to calculate the percentage.
But for fl = 0.9861948 this gives 1 (1.38052 casted to int).
If you want 2 instead, you could use Math.ceil:
int percentage = (int) Math.ceil((1 - fl) * 100); // gives 2
I wrote two methods below to convert a float number to a string displayed as percentage:
//without decimal digits
public static String toPercentage(float n){
return String.format("%.0f",n*100)+"%";
}
//accept a param to determine the numbers of decimal digits
public static String toPercentage(float n, int digits){
return String.format("%."+digits+"f",n*100)+"%";
}
Test Case1:
public static void main(String[] args) {
float f = 1-0.9861948f;//your number,0.013805211
System.out.println("f="+f);//f=0.013805211
System.out.println(toPercentage(f));//1%
System.out.println(toPercentage(f,2));//1.38%
}
Test Case2:
If you want 2% instead, try to input a param like this:
float f = 1-0.9861948f;//your number,0.013805211
f= (float)(Math.ceil(f*100)/100);//f=0.02
System.out.println("f="+f);f=0.02
System.out.println(toPercentage(f));//2%
System.out.println(toPercentage(f,2));//2.00%
When you output the float just tell the string conversion to only allow no/one/whatever trailing digits:
System.out.printf("We have downloaded: %.0f %%%n", (1-fl) * 100);
But I'm not sure why exactly you'd want to round 1.4% to 2%.. if you really want that it gets a lot more complicated for really no good reason.
How about (1.0 -fl ) * 100 ?
Convert this to an integer and you wouldn't have any issues.
Since percent means "per 100," perhaps you could multiple fl by 100. Since, for some reason, you want .98 to mean 2%, you would then subtract the result from 100.
You need something like:
float allSize = ...;
float downloaded = ...;
int percent = (allSize - downloaded/100 * 100.0)/allSize
(downloaded/100 * 100.0) - used for make two digit of fractional part;
After applying the ((1-fl)*100) logic you can use DecimalFormat or String.format().
float fl = ((float)20701682 / (float)20991474)*100;
int pct = 100 - Math.floor(fl)