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.
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 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);
Does anyone knows how to compute for the Area of a triangle using this formula in traditional java without changing or adding anything in the formula?
Area = 1/2*base*height
If i alter the formula like:
Area =
1.0f/2*baseheigh or 1/2.0fbase*height or 0.5*base*height
...this will definitely give me what I am looking for.
But what I am trying to do is using the formula Area=1/2*base*height as is. Someone told me their is a way but I can't seem to follow.
If this is my program:
public class Area {
public static void main (String[] args) {
// If this is the given value
int base = 5;
int height = 5;
float Area = 0;
//Using this formula without altering or adding anything on it
Area = 1/2*base*height;
System.out.println("Area = " +Area);
}
}
This will give out:
Area = 0.0
*How will I get:
Area = 12.5
Your issue is with integer arithmetic. Specifically, consider 1/2. Because we have int/int, the result must be an int (it can then be cast to a double, float, etc). However, because fractions don't exist in the int type, we get 1/2 = 0. Thus you have 1/2*base*height = 0 * base * height = 0.
Try 0.5*base*height, or 1.0/2.0*base*height, or (float)1 / (float)2 * base*height
Specifically, note that in (float)(1/2), the cast occurs too late - you'll get 0.0.
use double .int int mathematicians operation,s results always int in java
double base = 5;
double height = 5;
double Area = 0;
Area = 1.0/2*base*height;
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)