apache.commons.math distributions, get probability greater than 1 - java

I use apache commons math library for MixtureMultivariateNormalDistribution. And it appears that sometimes density() function returns me values that are very much greater than 1. What's it?
My mixture coefficients sum to 1 and my covariance matrices of each NormalDistribution are fine (since MixtureMultivariateNormalDistribution constructor doesn't throw any exception when i create the object) and means are fine too. Dimension is 39. And i have 3 normal distribution in a mixture. Is it some bug or what? Did anyone meet this problem?
Thanks

The cumulative distribution function is indeed something between 0 and 1. The DENSITY function, on the other hand, only has to be greater than or equal to zero; in particular, it is allowed to be greater than 1, so long as its integral (the cdf) is equal to 1.
For example, consider a single Gaussian bump centered at the origin. Its density function is exp(-1/2*x^2/sigma^2)/sigma/sqrt(2*pi). Its greatest value, at the origin, is 1/sigma/sqrt(2*pi), so for sigma < 1/sqrt(2*pi) (approximately 0.399), the peak is greater than 1.
If you are working with mixture components that have sufficiently small variance, the density can be greater than 1 in neighborhoods of their means.

"Returns the probability density function (PDF) of this distribution evaluated at the specified point x. In general, the PDF is the derivative of the cumulative distribution function. If the derivative does not exist at x, then an appropriate replacement should be returned, e.g. Double.POSITIVE_INFINITY, Double.NaN, or the limit inferior or limit superior of the difference quotient."
Does that help? I presume you're getting the limit superior of the difference quotient. Unfortunately I don't know what that means.

Related

Smart algorithm to randomize a Double in range but with odds

I use the following function to generate a random double in a specific range :
nextDouble(1.50, 7.00)
However, I've been trying to come up with an algorithm to make the randomization have higher probability to generate a double that is close to the 1.50 than it is to 7.00. Yet I don't even know where it starts. Anything come to mind ?
Java is also welcome.
You should start by discovering what probability distribution you need. Based on your requirements, and assuming that random number generations are independent, perhaps Poisson distribution is what you are looking for:
a call center receives an average of 180 calls per hour, 24 hours a day. The calls are independent; receiving one does not change the probability of when the next one will arrive. The number of calls received during any minute has a Poisson probability distribution with mean 3: the most likely numbers are 2 and 3 but 1 and 4 are also likely and there is a small probability of it being as low as zero and a very small probability it could be 10.
The usual probability distributions are already implemented in libraries e.g. org.apache.commons.math3.distribution.PoissonDistribution in Apache Commons Math3.
I suggest to not think about this problem in terms of generating a random number with irregular probability. Instead, think about generating a random number normally in a some range, but then map this range into another one in non-linear way.
Let's split our algorithm into 3 steps:
Generate a random number in [0, 1) range linearly (so using a standard random generator).
Map it into another [0, 1) range in non-linear way.
Map the resulting [0, 1) into [1.5, 7) linearly.
Steps 1. and 3. are easy, the core of our algorithm is 2. We need a way to map [0, 1) into another [0, 1), but non-linearly, so e.g. 0.7 does not have to produce 0.7. Classic math helps here, we just need to look at visual representations of algebraic functions.
In your case you expect that while the input number increases from 0 to 1, the result first grows very slowly (to stay near 1.5 for a longer time), but then it speeds up. This is exactly how e.g. y = x ^ 2 function looks like. Your resulting code could be something like:
fun generateDouble(): Double {
val step1 = Random.nextDouble()
val step2 = step1.pow(2.0)
val step3 = step2 * 5.5 + 1.5
return step3
}
or just:
fun generateDouble() = Random.nextDouble().pow(2.0) * 5.5 + 1.5
By changing the exponent to bigger numbers, the curve will be more aggressive, so it will favor 1.5 more. By making the exponent closer to 1 (e.g. 1.4), the result will be more close to linear, but still it will favor 1.5. Making the exponent smaller than 1 will start to favor 7.
You can also look at other algebraic functions with this shape, e.g. y = 2 ^ x - 1.
What you could do is to 'correct' the random with a factor in the direction of 1.5. You would create some sort of bias factor. Like this:
#Test
void DoubleTest() {
double origin = 1.50;
final double fiarRandom = new Random().nextDouble(origin, 7);
System.out.println(fiarRandom);
double biasFactor = 0.9;
final double biasedDiff = (fiarRandom - origin) * biasFactor;
double biasedRandom = origin + biasedDiff;
System.out.println(biasedRandom);
}
The lower you set the bias factor (must be >0 & <= 1), the stronger your bias towards 1.50.
You can take a straightforward approach. As you said you want a higher probability of getting the value closer to 1.5 than 7.00, you can even set the probability. So, here their average is (1.5+7)/2 = 4.25.
So let's say I want a 70% probability that the random value will be closer to 1.5 and a 30% probability closer to 7.
double finalResult;
double mid = (1.5+7)/2;
double p = nextDouble(0,100);
if(p<=70) finalResult = nextDouble(1.5,mid);
else finalResult = nextDouble(mid,7);
Here, the final result has 70% chance of being closer to 1.5 than 7.
As you did not specify the 70% probability you can even make it random.
you just have to generate nextDouble(50,100) which will give you a value more than or equal 50% and less than 100% which you can use later to apply this probability for your next calculation. Thanks
I missed that I am using the same solution strategy as in the reply by Nafiul Alam Fuji. But since I have already formulated my answer, I post it anyway.
One way is to split the range into two subranges, say nextDouble(1.50, 4.25) and nextDouble(4.25, 7.0). You select one of the subranges by generating a random number between 0.0 and 1.0 using nextDouble() and comparing it to a threshold K. If the random number is less than K, you do nextDouble(1.50, 4.25). Otherwise nextDouble(4.25, 7.0).
Now if K=0.5, it is like doing nextDouble(1.50, 7). But by increasing K, you will do nextDouble(1.50, 4.25) more often and favor it over nextDouble(4.25, 7.0). It is like flipping an unfair coin where K determines the extent of the cheating.

How can i generate this special type of probability?

I'm creating a Java application that needs to randomly generate numbers with probabilities. These float numbers (or doubles doesn't change much) must be from 0 to 100 where 0 and 100 have the lowest probability of coming out while 50 (which is the middle) is the one with the highest probability... practically, moving away from the center the rarity that comes out that number is always greater until it becomes almost impossible. For example the number 99.9 comes out 1 time in 5 billion, but as I said it is just an example so the rarity of the numbers must be established by the function. Basically I would like to say that the closer you get to 100 or 0, the rarity tends to infinity.
However, I would like it to be a function with a min parameter and a max parameter to make it more versatile.
(Sorry if the question is not very clear but i'm not native and i'm still learning english...)
Perhaps you could use Random's nextGaussian() method which generates a random number based on the default mean of 0.0 and standard deviation of 1.0. In your case, I believe the mean would be 50, and you could calculate the standard deviation so that it fits your requirements. You could use this link: Java normal distribution in order to help answer your question.
Docs for Random.nextGaussian().
I would also suggest looking into normal distributions because I believe the match what you are asking for.
Hope that helped!

Using a low pass filter to calculate average?

If I want to calculate an average of 400 data points (noise values from an accelerometer sensor), can I use a low pass function such as this one to do that?
private float lowPass(float alpha, float input, float previousOutput) {
return alpha * previousOutput + (1 - alpha) * input;
}
I'm comparing this to simply storing the 400 data points in a List<float>, summing them up and dividing by 400.
I'm getting quite different results even with high values for alpha. Am I doing something wrong? Can I use the low pass filter to calculate an average, or is it generally better to simply calculate the "real" average?
EDIT
My low pass function originally took a float[] as input and output, since my data comes from a 3-axis accelerometer. I changed this to float and removed the internal for loop to avoid confusion. This also means that the input/output is now passed as primitive values, so the method returns a float instead of operating directly on the output array.
If you can afford to compute the arithmetic mean (which doesn't even require extra storage if you keep a running sum) then that would probably be the better option in most cases for reasons described bellow.
Warning: maths ahead
For sake of comparing the arithmetic average with the first-order recursive low-pass filter you are using, let's start with a signal of N samples, where each sample has a value equal to m plus some Gaussian noise of variance v. Let's further assume that the noise is independent from sample to sample.
The computation of the arithmetic average on this signal will give you a random result with mean m and variance v/N.
Assuming the first previousOutput is initialized to zero, deriving the mean and variance for the last output (output[N-1]) of the low-pass filter, we would get a mean m * (1 - alpha^N) and variance v * (1-alpha)^2 * (1-alpha^(2*N)) / (1 - alpha^2).
An immediate problem that can be seen is that for large m, the estimated mean m * (1 - alpha^N) can be quite far for the true value m. This problem unfortunately gets worse as alpha gets closer to 1. This occurs because the filter does not have time to ramp up to it's steady state value.
To avoid this issue, one may consider initializing the first previousOutput with the first input sample.
In this case the mean and variance of the last output would be m and v * ((1-alpha)^2*(1-alpha^(2*N-2))/(1-alpha^2) + alpha^(2*N-2)) respectively. This time the problem is that for larger alpha the output variance is largely dominated by the variance of that first sample that was used for the initialization. This is particularly obvious in the following comparative graph of the output variance (normalized by the input variance):
So, either you get a bias in the estimated mean when initializing previousOutput with zero, or you get a large residual variance when initializing with the first sample (much more so than with the arithmetic mean computation).
Note in conclusion that actual performance may vary for your specific data, depending on the nature of the observed variations.
What's output[] ? If it holds the results and you initialize with 0s, then this term will always be zero: alpha * output[i]
And in general:
A low-pass filter is a filter that passes signals with a frequency
lower than a certain cutoff frequency and attenuates signals with
frequencies higher than the cutoff frequency.
So it is not average it is basically a cutoff up to a specific threshold.

Do an action with some probability in java

In Java, I am trying to do an action with a probability p. p is a float variable in my code. I came up with this way of doing it:
if( new Random().nextFloat() < p)
do action
I wanted to confirm if this is the correct way of doing it.
There is a TL;DR at the end.
From javadocs for nextFloat() (emphasis by me):
public float nextFloat()
Returns the next pseudorandom, uniformly distributed float value
between 0.0 and 1.0 from this random number generator's sequence.
If you understand what uniform distribution is, knowing this about nextFloat() is going to be enough for you. Yet I am going to explain a little about uniform distribution.
In uniform distribution, U(a,b) each number in the interval [a,b], and also all sub-intervals of the same length within [a,b] are equally probable, i.e. they have equal probability.
In the figure, on the left is the PDF, and on the right the CDF for uniform distribution.
For uniform distribution, the probability of getting a number less than or equal to n, P(x <= n) from the distribution is equal to the number itself (look at the right graph, which is cumulative distribution function for uniform distribution). That is, P(x <= 0.5) = 0.5, P(x <= 0.9) = 0.9. You can learn more about uniform distribution from any good statistics book, or some googling.
Fitting to your situation:
Now, probability of getting a number less than or equal to p generated using nextFloat() is equal to p, as nextFloat() returns uniformly distributed number. So, to make an action happen with a probability equal to p all you have to do is:
if (condition that is true with a probability p) {
do action
}
From what is discussed about nextFloat() and uniform distribution, it turns out to be:
if(randObj.nextFloat() <= p) {
do action
}
Conclusion:
What you did is almost the right way to do what you intended. Just adding the equal sign after < is all that's needed, and it doesn't hurt much to leave out the equal sign either!
P.S.: You don't need to create a new Random object each time in your conditional, you can create one, say randObj before your loop, and then invoke its nextFloat() method whenever you want to generate a random number, as I have done in my code.
Comment by pjs:
Take a look at the comment on the question by pjs, which is very important and well said. I quote:
Do not create a new Random object each time, that's not how PRNGs are
meant to be used! A single Random object provides a sequence of values
with good distributional properties. Multiple Random objects created
in rapid succession are 1) computationally expensive, and 2) may have
highly correlated initial states, thus producing highly correlated
outcomes. Random actually works best when you create a single instance
per program and keep drawing from it, unless you really really know
what you're doing and have specific reasons for using correlation
induction strategies.
TL;DR
What you did is almost the right way to do it. Just adding the equal sign after < (to make it <=) is all that's needed, and it doesn't hurt much to leave out the equal sign either!
Yes. That is correct (from a pure probability perspective). Random().nextFloat() will generate a number between 0.0 and 1.0 exclusive. So as long as your probability is as a float in the range 0.0 and 1.0, this is the correct way of doing it.
You can read more of the exact nextFloat() documentation here.

Normalized Iteration Count does not work. What am I doing wrong?

As you can see from the title, I'm busy programming a little programm for visualizing fractals in Java. Anybody who deals with fractals will come to the point where he/she searches for a solution to get these stupid "bands" away, when you just colour a pixel by the number of iterations it took to escape.
So I searched for a more advanced colouring algorithm, finding the "normalized iteration count". The formula I'm using is:
float loc = (float) 1 - Math.log(Math.log(c.abs())) / Math.log(2);
Everybody on the Internet is so happy about this algorithm, everybody uses it, everbody gets great results. Except me. I thought, this algorithm should provide a float between 0 and 1. But that doesn't happen. I did some calculations and came to the conclusion, that this algorithm only works for c.abs() >= Math.E && c.abs() <= Math.exp(2) (that is Math.E * Math.E).
In numbers this means, my input into this equation has to be between about 2.718 and 7.389.
But a complex number c is considerd to tend towards infinity when its magnitude gets greater than 2. But for any Input smaller than Math.E, I get a value greater than one. And for any number greater than Math.exp(2), it gets negative. That is the case if a complex number escapes really fast.
So please tell me: what am I doing wrong. I'm desperate.
Thanks.
EDIT:
I was wrong: the code I posted is correct, I just
1. used it the wrong way and so it didn't provide the right output.
2. had to set the bailout value of the mandelbrot/julia algorithm to 10, otherwise I would've got stupid bands again.
Problem solved!
As you've already discovered, you need to increase the bailout radius before smoothing will look right.
Two is the minimum length that a coordinate can have such that when you square it and add the initial value, it cannot result in a smaller length. If the previous length was 2.0, and you squared it, you'd have a length of 4.0 (pointing in whichever direction), and the most that any value of c could reduce that by is 2.0 (by pointing in precisely the opposite direction). If c were larger than that then it would start to escape right away.
Now, to estimate the fractional part of the number of iterations we look at the final |z|. If z had simply been squared and c not added to it, then it would have a length between 2.0 and 4.0 (the new value must be larger than 2.0 to bail out, and the old value must have been less than 2.0 to have not bailed out earlier).
Without c, taking |z|'s proportional position between 2 and 4 gives us a fractional part of the number of iterations. If |z| is close to 4 then the previous length must have been close to 2, so it was already close to bailing out in the previous iteration and the smoothed result should be close to the previous iteration count to represent that. If it's close to 2, then the previous iteration was further from bailing out, and so the smoothed result should be closer to the new iteration count.
Unfortunately c messes that up. The larger c is, the larger the potential error is in that simple relationship. Even if the old length was nearly at 2.0, it might have landed such that c's influence made it look like it must have been smaller.
Increasing the bailout mitigates the effect of adding c. If the bailout is 64 then the resulting length will be between 64 and 4096, and c's maximum offset of 2 has a proportionally smaller very impact on the result.
You have left out the iteration value, try this:
float loc = <iteration_value> + (float) 1 - Math.log(Math.log(c.abs())) / Math.log(2);
The iteration_value is the number of iterations which yielded c in the formula.

Categories