Math in JavaBean - java

I have tried a few different ways to write this problem out and I keep on having issues. So I have 5 categories that need to be averaged out. Here is just a sample code of one part of the code:
public double getAvg() {
String[] Avg = new String[]{Q1, Q2, Q3, Q4};
int sum = 0;
for (String input : Avg) {
sum += Integer.parseInt(input);
}
return sum * (10);
}
So there are 4 other similar sections like this. Anyway, I need to take these 5 results and have them post a total using this equation:
(((part1)*(.35))+((part2)*(.15))+((part3)*(.10))+((part4)+(.20))+((part5)*(.20)))=100%
-
So, I need to clarify. I am writing a javabean that gets and overall average of statistics input by the user. There are 5 sections that need to be evaluated to get an overall average of the given statistics. I have written three convenience methods to get the first three averages(one of these is what is shown above in the example code). The last 2 values are input by the user.
So what I need is to write a convenience method in the bean that gets the averages in the manner shown above and takes the two additional values input by the user and then spits out an overall average using this rubric:
Value A: 35% of overall average
Value B: 15% of overall average
Value C: 10% of overall average
Value D: 20% of overall average
Value E: 20% of overall average.
The trouble that I am having is I don't know how to factor in the answers of the three convenience methods into the overall average convenience method.
Any help is appreciated!

Related

Is the 0/1 knapsack algorithm a suitable candidate here?

I have three categories of input , each with a impact range.
Cat 1 : 20 - 16
Cat 2 : 15 - 5
Cat 3 : 4 -1
I have a file with say N randomly generated categories.
I am trying to take a sum of impact for all the 100 entries through a logic that looks something like this :
// calculate sum of impacts
getSum(){
Generate a random class with seed as current system execution time
for(as many entries in file){
switch(category)
case 1 : i = random input between 20 - 16
case 2 : i = random input between 15 - 5
case 3 : i = random input between 4 - 1
some default case here
sum = sum + i
}
return sum
}
.
.
// loop until you get a desired sum
while(true){
if(Call to getSum() returns value within a desired range){
display some statistics;
break;
}
}
However , i see that the program generally runs infinitely , as the random generation and subsequent summation is giving result beyond the desired range. So , to get things in range , I have to manually tune the max-min ranges for each execution.
Can someone suggest an algorithm that will automatically vary the max min ranges for each category , by learning the trend of obtained sum as the program is running , so as to quickly give a solution ?
Edit : i have just read about the 0/1 knapsack algorithm.. and it seems promising , but unsure if that is the algorithm for this case. Any help would be great.
A couple band-aids:
1) use a long int instead of a regular int t give you a longer range.
2) use an unsigned long, since all of your relevant numbers are positive (then be careful of underflow errors when you subtract.
A couple possible strategies:
1) (This contradicts your question, but it is how things are usually done.) Determine the static maximum for each category, and design to it, using long unsigned int if that is large enough, or some larger data structure as necessary.
2) (This is exactly what you are asking.) Use, and build if necessary, a data structure which expands when an overflow occurs.
Solution for strategy 2:
I will get back to you on this. :)

What could Error in this java program to compute sine?

I have written this code to compute the sine of an angle. This works fine for smaller angles, say upto +-360. But with larger angles it starts giving faulty results. (When I say larger, I mean something like within the range +-720 or +-1080)
In order to get more accurate results I increased the number of times my loop runs. That gave me better results but still that too had its limitations.
So I was wondering if there is any fault in my logic or do I need to fiddle with the conditional part of my loop? How can I overcome this shortcoming of my code? The inbuilt java sine function gives correct results for all the angles I have tested..so where am I going wrong?
Also can anyone give me an idea as to how do I modify the condition of my loop so that it runs until I get a desired decimal precision?
import java.util.Scanner;
class SineFunctionManual
{
public static void main(String a[])
{
System.out.print("Enter the angle for which you want to compute sine : ");
Scanner input = new Scanner(System.in);
int degreeAngle = input.nextInt(); //Angle in degree.
input.close();
double radianAngle = Math.toRadians(degreeAngle); //Sine computation is done in terms of radian angle
System.out.println(radianAngle);
double sineOfAngle = radianAngle,prevVal = radianAngle; //SineofAngle contains actual result, prevVal contains the next term to be added
//double fractionalPart = 0.1; // This variable is used to check the answer to a certain number of decimal places, as seen in the for loop
for(int i=3;i<=20;i+=2)
{
prevVal = (-prevVal)*((radianAngle*radianAngle)/(i*(i-1))); //x^3/3! can be written as ((x^2)/(3*2))*((x^1)/1!), similarly x^5/5! can be written as ((x^2)/(5*4))*((x^3)/3!) and so on. The negative sign is added because each successive term has alternate sign.
sineOfAngle+=prevVal;
//int iPart = (int)sineOfAngle;
//fractionalPart = sineOfAngle - iPart; //Extracting the fractional part to check the number of decimal places.
}
System.out.println("The value of sin of "+degreeAngle+" is : "+sineOfAngle);
}
}
The polynomial approximation for sine diverges widely for large positive and large negative values. Remember, since varies from -1 to 1 over all real numbers. Polynomials, on the other hand, particularly ones with higher orders, can't do that.
I would recommend using the periodicity of sine to your advantage.
int degreeAngle = input.nextInt() % 360;
This will give accurate answers, even for very, very large angles, without requiring an absurd number of terms.
The further you get from x=0, the more terms you need, of the Taylor expansion for sin x, to get within a particular accuracy of the correct answer. You're stopping around the 20th term, which is fine for small angles. If you want better accuracy for large angles, you'll just need to add more terms.

probability and programming simulation

I'm having some trouble understanding the following result.
I want to know if the following code is actually correct. It stumps me - but that could be due to me misunderstanding the probability involved.
The code should speak for itself, but to clarify the 'real world' simulation represents 2 people flipping a coin. When you lose you pay 1 dollar, when you win you win a dollar. An even sum game!
private static Random rnd = new Random();
public static void main(String[] args) {
int i=0;
for (int x = 0; x<1000000; x++) {
if (rnd.nextBoolean()) i+=1;
else i-=1;
}
System.out.println(i);
}
When I run this however I get huge swings! Whilst I would expect a large sample like this to converge to 0, I'm seeing +-4000
Not only that but increasing the sample size seems to only make the swings higher.
Am I misusing the random function ? :P
I think you're good. The thing to look at is the ratio of the swing to your sample.
4000 out of 1000000 for example is 0.4%
If you increase the sample size, you should expect that ratio to go down.
The results of your experiment should follow a binomial distribution. If the
number of trials is N, and the probability of success p=1/2, then the
number of successes N_success (for large enough N) should have a mean of approximately Np,
and standard deviation sqrt(N*p*(1-p)).
You're actually tracking K = (N_success - N_fail). So N_success = N/2 + K/2.
With 1,000,000 trials and K=4000, we get N_success = 502000. The expected
value is 500000, with standard deviation sqrt(250000) = 500. The difference
between the observed and expected values of N_success is 2000, or about 4 sigma.
That's significant enough to question whether the random number generator is
biased. On the other hand, if you're running this test thousands of times,
you'd expect a few outliers of this magnitude, and you seem to be seeing both
positive and negative values, so in the long run maybe things are OK after all.
You are simulating a one-dimensional random walk. Basically, imagine yourself standing on a line of integers. You begin at point i=0. With equal probability you take a step to the right or the left.
The random walk has a few cool properties and you've touched on my favourite:
Starting at point i=0, as N gets larger, the probability that you will return to that point approaches 1. As you point out - a zero sum game.
However, the expected time it will take you to return there tends to infinity. As you notice, you get some very large swings.
Since the average value should be 0 and the variance of N moves is N, then you would expect 95% of your simulations to end in the region: (- 1.96, 1.96)*N^(0.5).

calculate average based on 1 number only

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.

JSR 275 - Units, Percent per second

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.

Categories

Resources