How to calculate percentage ( or average) when You have dividend but not deviser?
You have a lot of values, and some of them figure into your average - or percentage - and some of them probably don't. You are not expressing the problem clearly enough for anyone to be able to give you a meaningful answer.
A percentage represents a fraction, one value divided by another (multiplied by 100 to express it in percentage, but that's trivial and not part of the problem). What is the value that represents 100%? And what value are you trying to assign? In what way do you think that the quantity of bonuses should affect the percentage?
Some possible answers:
The total bonus earned by an individual, as compared to her nominal salary. If she earns $50k and her bonus is $20K, that is 20/50 *100 = 40%.
The total bonus earned by an individual, as compared to all the bonuses given out that year. If she received the same $20K, but the company gave out $100K in bonuses, then the percentage is 20/100 * 100 = 20%.
The most recent bonus earned by an individual, as compared to all bonuses awarded to her this year. If she got $5K for her last bonus, and the total was $20, that's 5/20 * 100 = 25%.
We really don't have enough information to go on; it could be any of these, or something entirely different. It is entirely possible to have a percentage value greater than 100%.
The average of one value is that value (Total number=1).
But this probably means I don't understand your question.
Without knowing the number of years, you need to know something else about the range of bonuses possible. i.e. does it have to be a whole number between 15 - 25%. However, this is largely guessing.
To get an average, you need a total and a count. BTW: In your case you want the geometric average, but you need to know the same things.
If your input is a list of numbers, showing percentage values means you need to compute the total and then see how much of the total each of them is:
For instance, if you have 110, 110, 110, you'll have a total of 330 and each of the values will be shown as 110/330 = 0.33 = 33% of the total.
In addition, if I have three decimal
values 120, 4420, and 230. How can I
get a number less than 1 that
represent the average of these 3
values?
You cannot. The average of those 3 numbers will be (120 + 4420 + 230) / 3. That will never be less than one. Maybe you are confused about what average means?
You need to be more specific or give an example. But I will give an answer based off of what I THINK you mean.
You cannot find the average of one lone number. If you were saying a temperature of 125 degrees every hour you could do it, The answer would obviously be 125. It is the closest thing that I can think of to what you are asking. You need to be more specific or the problem cannot be done. Otherwise use the simple formula: Sum/Number of integers. Also known as the mean. So that would be 125/1, which is still 125.
Related
I'm trying to round the cents of a value.
The rounding seems to work, but there's an exception:
double amount = 289.42;
String f= String.format("%.1f", amount);
System.out.println(new DecimalFormat("##0.00").format(Double.valueOf(f)));
This is the error: java.lang.NumberFormatException: For input string: "289,4"
Your question posits an impossibility.
Here's the thing: You cannot represent currency amounts with double. At all. Thus, 'how do I render these cents-in-a-double appropriately' isn't a sensible concept in the first place. Because cents cannot be stored in a double.
The problem lies in what double are, fundamentally. double is a numeric storage system that is defined to consist of exactly 64 bits. That's a problem right there: It's a mathematical fact that 64 bits can store at most 2^64 unique things, because, well, math. Think about it.
The problem is, There are in fact an infinite amount of numbers between 0 and 1, let alone between -infinity and +infinity which double would appear to represent. So, how do you square that circle? How does one represent one specific value chosen from an infinite amount of infinities, with only 64 bits?
The answer is simple. You don't.
doubles do not in fact store arbitrary values at all. And that is why you cannot use them to store currencies. Instead, take the number line and mark off slightly less than 2^64 specific values on it. We'll call these 'the blessed numbers'. A double can only store blessed numbers. They can't store anything else. In addition, any math you do to doubles is silently rounded to the nearest blessed value as doubles can't store anything else. So, 0.1 + 0.1? Not actually 0.2. Instead, 0.1 isn't even blessed, so that's really round-to-blessed(0.1) + round-to-blessed(0.1), so actually that's 0.0999999999975 + 0.0999999999975 = 0.2000000000018 or whatever. The blessed numbers are distributed unequally - there are a ton of blessed numbers in the 0-1 range, and as you move away from the 0, the distance between 2 blessed numbers grows larger and larger. Their distribution makes sense, but, computers count in binary, so they fall on neat boundaries in binary, not in decimal (0.1 looks neat in decimal. It's similar to 1 divided by 3, i.e. endlessly repeating, and therefore not precisely representable no matter how many bits you care to involve, in binary).
That rounding is precisely what you absolutely don't want to happen when representing currency. You don't want a cent to randomly appear or disappear and yet that is exactly what will happen if you use double to store finance info.
Hence, you're asking about how to render 'cents in a double' appropriately but in fact that question cannot possibly be answered - you can't store cents in a double, hence, it is not possible to render it properly.
Instead..
Use cents-in-int
The easiest way to do currency correctly is to first determine the accepted atomary unit for your currency, and then store those, in long or int as seems appropriate. For euros, that's eurocents. For bitcoin, that's satoshis. For yen, it's just yen. For dollars, its dollarcents. And so on.
$5.45 is best represented as the int value 545. Not as the double value 5.45, because that's not actually a value a double can represent.
Why do doubles show up as 0.1?
Because System.out.println knows that doubles are wonky and that you're highly likely to want to see 0.1 and not 0.09999999999991238 and thus it rounds inherently. That doesn't magically make it possible to use double to represent finance amounts.
I need to divide, or multiply by complex factors
Division for currency is always nasty. Imagine a cost of 100 dollars that needs to be paid by each 'partner' in a coop. The coop has 120 shares, and each partner has 40 shares, so each partner must pay precisely 1/3 of the cost.
Now what? 100 dollars does not neatly divide into threes. You can't very well charge everybody 33 dollars, 33 cents, and a third of a cent. You could charge everybody 33.33, but now the bank needs to eat 1 cent. You could also charge everybody 33.34, and the bank gets to keep the 2 cents. Or, you could get a little creative, and roll some dice to determine 'the loser'. The loser pays 33.34, the other 2 pay 33.33.
The point is: There is no inherently correct answer. Each situation has its own answer. Hence, division in general is impossible without first answering that question. There is no solving this problem unless you have code that knows how to apply the chosen 'division' algorithm. a / b cannot be used in any case (as the operation has at least 3 params: The dividend, the divisor, and the algorithm to apply to it).
For foreign exchange, 'multiply by this large decimal value' comes up a lot. You can store arbitrary precision values exactly using the java.math.BigDecimal class. However, this is not particularly suitable for storing currencies (all multiplication-by-a-factor will mean the BDs grow ever larger, they still can't divide e.g. 1 by 3 (anything that has repeating digits), and they don't solve the more fundamental issue: Any talk with other systems, such as a bank, can't deal with fractions of atomary units). Stick with BD-space math (as that is perfect, though, can throw exceptions if you divide, and grows ever slower and more complicated over time), until the system you are programming for enforces a rounding to atomary units, at which point, you round, resetting the growth. If you never need to multiply by fractions this doesn't come up, and there's no need to use BigDecimal for anything currency related.
How do I format cents-in-a-long?
String.format("€%d.%02d", cents / 100, cents % 100);
It gets very slightly more complicated for negative numbers (% returns negative values, so you need to do something about this. Math.abs can help), but not very.
cents / 100 gives you the "whole" part when you integer-divide by 100, and % 100 gives you the remainder, which precisely boils down to 'euros' and 'eurocents'.
Disclaimer: This is a very very difficult question about mathematics and algorithms (in my opinion) - so respect to anyone who makes this. I admire you.
I would like to evaluate the performance of my employees. I would like to do this by measuring the following parameters as percentages of the amount of time they spend working:
1. % of Time spent working
2. % of Time spent in meetings
3. % of Time spent travelling
I have a "preferred" set of percentages for each of these. This represents the ideal time that I would LIKE my employees to spend their time.
% Time spent in Meetings -> 30%
% Time spent Travelling -> 10%
% Time Spent Working -> 60%
total time spent on activities: 100%
So in words, I would like my employees to spend 30% of their time in meetings, 10% time travelling and 60% on a desk working.
I would ALSO like to add weights to these different percentages. The weight would represent how "lenient" I am with each percentage being different to what I desire. In other words, how important I find it for each variable to be closest to the desired percentages (30, 10, 60). I would like to apply the weights on a scale of.1 to 10, 10 being most important, 1 being least important.
Meetings -> 3
Travelling -> 9
Working -> 5
So given the percentage of time spent by an employee, and the weight of the importance of the time spent being close to the desired time spent, I would like to generate an index between 0 and 100 where 100 is the perfect time percentages and 0 is the worst. So a score of 100 would give the "preferred" percentages:
% Time spent in Meetings -> 30%
% Time spent Travelling -> 10%
% Time Spent Working -> 60%
How I would try to approach this:
Find out what the minimum and maximum ratios are
Calculate a value to tell how far away each value is from the desired value using the minimum and maximum ratios. Make sure this value is in the ratio 0-1 (corresponding to 0-100)
Calculate a weighted average.
I think you're trying something which is kinda like the H-score.
H-score is a scored we use in digital pathology to measure tumor positivity for a maker and it is meant to weight the number of positive cells by their intensity.
It's:
1* (% of positive cells with score 1) + 2*(% of positive cells with score 2) + 3*(% of positive cells with score 3)
You could calculate the same as:
3*(1-% of difference between actual worked hourse and planned ones)
9*(1-% of difference between actual worked hourse and planned ones)
5*(1-% of difference between actual worked hourse and planned ones)
Don't forget to use absolute value when you compute the difference.
I used 1-% so that a difference of 0.8 (as planned 0.ì and worked 0.9) will result in a score of 0.2. This will work for the opposite situation too (planned 0.9 and worked 0.1).
In this way, who perfectly matches the planned hourse will have a score of 1700%.
Then just:
Score/Total weights = score between 0-100%.
This question already exists:
Closed 10 years ago.
Possible Duplicate:
How to format an integer to have two decimals?
I am struggling with this piece of code here.
DecimalFormat df = new DecimalFormat("00.##");
df.setMinimumFractionDigits(2);
return df.format(Integer.valueOf(amount));
Here's what I need:
Input: 2, Output: 2.00
Input 20, Output: 20,00
Input 1003, Output: 100,30
Input 120323, Output: 1.203,23 (a thousand two hundred and three and twenty three cents)
I can't use DecimalFormat because I don't have a pattern "example ##.##".
I should always have two decimals. If the amount is less that 100, then I only have to take the amount itself and add ".00" If it is bigger than 100, means that the two last digits are the two decimals I need. They are the cents.
Can anyone help me?
If you want to add two decimal places (which will always be .00 which is a bit redundant.
return String.format("%.2f", amount > 100 ? amount/100.0 : (double) amount);
I suggest you keep one set of units. You should be able to always use cents. If you don't do this you are likely to get confusion. For example, you have 100 and 10000 which are both 100.00
If the amount is less that 100, then I only have to take the amount
itself and add ".00" If it is bigger than 100, means that the two last
digits are the two decimals I need.
First you need to fix this problem. A class, or a native type, should only hold one kind of data, and should not burden other classes or code with detailed knowledge of how that data is to be handled depending on circumstances.
Get that thing to either return back numbers of pennies in all cases, or get it to return a number that supports decimal points. The better solution is numbers of pennies.
That way you don't have to put logic in your formatting, which certainly won't be there the second time you need to format the same thing.
I am performing a boolean query with multiple terms. I only want to process results with a score above a particular threshold. My problem is, I don't understand how this value is calculated. I understand that high numbers mean its a good match, and low numbers mean its a bad match, but there doesn't seem to be any upper bounds?
Is it possible to normalize the scores over the range [0,1]?
Here is a page describing how scores are calculated in Lucene:
http://lucene.apache.org/java/3_0_0/scoring.html
The short answer is that the absolute values of each document's score doesn't really mean anything outside the context of a given search result set. In other words, there isn't really a good way of translating the scores to a human definition of relevance, even if you do normalize the scores.
That being said you can easily normalize the scores by dividing each hit's score by the maximum score. So if the first hit's score is 2.5, then divide every hit's score by 2.5, and you'll get a number in between 0 and 1.
I need to represent the unit of Percent per second using the JScience.org's JSR 275 units and measures implementation. I am trying to do to the following:
Unit<Dimensionless> PERCENT_PER_SECOND = NonSI.PERCENT.divide(Si.SECOND).asType(Dimensionless.class)
but I am getting a ClassCastException when I try to do that.
The following works, but I'm not sure if there's a better way:
public interface PercentOverTime extends Quantity {}
public static Unit<PercentOverTime> PERCENT_PER_SECOND = new BaseUnit<PercentOverTime>("%/s");
Any thoughts? The closest I could find to this is the question on Cooking Measurements (which is how I saw how to define your own units).
I wrote up this code sample to test out the math here:
public void testUnit() {
// define two points on a function from t -> %
// the rate of change between these two points
// should have unit %/t
Measure<Double, Dimensionless> p0 = Measure.valueOf(50.0, NonSI.PERCENT);
Measure<Double, Dimensionless> p1 = Measure.valueOf(20.0, NonSI.PERCENT);
Measure<Double, Duration> timeDifference = Measure.valueOf(10.0, SI.SECOND);
// JSR-275 has no Amount, so have to convert and do math ourselves
// these doubles are percents
double p0Raw = p0.doubleValue(NonSI.PERCENT);
double p1Raw = p1.doubleValue(NonSI.PERCENT);
// this duration is in seconds
double timeDifferenceRaw = timeDifference.doubleValue(SI.SECOND);
// this is the slope of the secant between the two points
// so it should be the %/s we want
double rateSecant = (p1Raw - p0Raw) / timeDifferenceRaw;
// let's see what we get
Measure<Double, ?> answer = Measure.valueOf(rateSecant,
NonSI.PERCENT.divide(SI.SECOND));
System.out.println(answer);
}
If your original function has time as the independent variable (e.g. as seconds) and a ratio as the independent variable (e.g. as a percent), then the derivative of this function with regard to time will still have time as the independent variable, but will have 'ratio per time' as the dependent.
Yes, ratios are dimensionless, so this is a little bit odd, but you could imagine a graph of the percent change day over day in a stock price and then a graph of the change in the percent change in a stock price day over day day over day.
So what does this print out?
-3.0 %/s
Which is what we expect the rate of change to be for a change from 50 to 20 percent over 10 seconds.
So your unit construction should look like:
Unit<?> magicUnit = NonSI.PERCENT.divide(SI.SECOND);
Dimension magicDimension = Dimension.NONE.divide(Dimension.TIME);
System.out.println(magicUnit + " measures " + magicDimension + " ("
+ magicUnit.getDimension() + ")");
Indeed this prints %/s measures 1/[T] (1/[T]), as we expect.
So we have a Unit and Dimension and can make Measures. What is the Quantity we are measuring? The docs say this about Quantity:
Distinct quantities have usually
different physical dimensions;
although it is not required nor
necessary, for example Torque and
Energy have same dimension but are of
different nature (vector for torque,
scalar for energy).
So while Frequency would seem to be the correct Quantity, it doesn't really express the semantic quantity we seem to be discussing.
In closing, your first line of code doesn't work because in the included model 1/[T] measures the quantity Freqency, not the quantity Dimensionless. So if you don't want to make your own Quantity, use Unit. The Dimension you are looking for is None/Time, or %/second if you want the correct scalar multipliers in there. Finally, it's up to you whether you want to make your own Quantity, but it might be worthwhile if you're using this in a lot of places.
It would also be worthwhile to check out the latest developments in the JScience space since it seems like they decided Amount (with add, subtract, multiply, divide, pow, etc. methods) was needed. It would be really easy to do all this dimensional analysis with Amount. Just do a Percent Amount minus a Percent Amount and divide by a Seconds amount and it should do the units for you.
It has units s^-1, or Hz (SI.HERTZ in JScience speak).
Or Unit<Frequency>.
Percent isn't a unit, but a scalar - so percent per second is only a scalar value per unit time, which doesn't make sense. It's like saying "3 per second". 3 what?
If you incorporate the unit of what you are measuring per unit time that will get you the correct unit.