Let's suppose x ~ Poisson(2.5); I would like to calculate something like E(x | x > 2).
I assumed that this could be done with the .dist.expect operator, i.e.:
D = stats.poisson(2.5)
cond_expect = D.dist.expect(lambda x: x, D.args,lb=2)
This evaluates to cond_expect = 2.29478750344
However, if I just calculate the mean of a random sample from that distribution
D = stats.poisson(2.5)
test = D.rvs(size = 100000)
empirical_expectation = np.mean(test[test>=2])
empirical_expectation evaluates to 3.20875563063.
If anyone could clarify what I'm misunderstanding about the API, it would be greatly appreciated.
The method expect takes a Boolean parameter conditional, which is False by default. Set it to True:
cond_expect = D.dist.expect(lambda x: x, D.args, lb=2, conditional=True)
returns 3.219839256818051 in agreement with empirical result.
What this does:
conditional : bool, optional
If true then the expectation is corrected by the conditional probability of the summation interval. The return value is the expectation of the function, func, conditional on being in the given interval (k such that ul <= k <= ub). Default is False.
So, if False then you get E(X if X >= 2 else 0) instead of conditional expectation, which is adjusted by division by P(X >= 2): E(X | X >= 2) = E(X if X >= 2 else 0) / P(X >= 2)
I don't know why you would ever want conditional=False when providing an upper or lower bound, but it's the default.
Related
I'm trying to create a function that would verify if a value is within chosen boundaries and if it's not, the user must retry until verification.
I wanted to know why my code skips the if condition for any given value and it returns me for the input prompt : "Error: Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error."
A=limit(5pi/6,-pi/2,pi/2) for example jumps directly to the else condition while it's true for the if condition
Here is my code :
function alpha = limit(pos,min,max)
if (pos >= max) && (pos <= min)
alpha=pos;
else
while pos >= max || pos <= min
prompt = 'Enter value between max and min';
alpha = input(prompt);
end
end
end
The function first checks whether pos is both greater than or equal to max and less than or equal to min.
I expect you intend max to be greater than min. Therefore, the if line should be:
if (pos <= max) && (pos >= min)
I assume your val_max/val_min are typos (and should be max/min) Then, your while loop depends on the value of pos. But pos is never updated in the loop, so your loop is just going to iterate forever.
You need to update pos inside the while loop for this to work. Try something like this:
function alpha = limit(pos,min,max)
while pos > max || pos < min
prompt = 'Enter value between min and max';
pos = input(prompt);
end
alpha = pos;
end
I have say 100 elements that I want to assign to say 10 spots.
# the elements list holds 100 variables that signify the assignment to a spot
elements = [model.NewIntVar(1, 10) for i in range(100)]
Each of my element has a specific size. Now I want to model one (set of) constraint(s) per spot that says: The added sizes of all elements assigned to this spot lies in a fixed range.
So if spot 1 gets elements 1, 16 and 64 assigned, and their sizes are 1521, 1732, 1431 and my range is (3000, 6000) that would be ok. But if too many or too large elements (or too few/small) get assigned to spot 1, that would not be ok.
Something like the following, which does not work:
for spot in range(10):
sum_ = sum([get_size(e) for e in elements if e == spot]) # if think if e == spot is what fails
model.Add(sum_ >= 3000)
model.Add(sum_ <= 6000)
How can I model such a thing? I have looked at channeling constraints but I can't quite wrap my head around it.
I think it is better to model the assignment as a boolean:
from ortools.sat.python import cp_model
model = cp_model.CpModel()
solver = cp_model.CpSolver()
all_spots = range(10)
all_elems = range(100)
elements = {
(elem, spot): model.NewBoolVar(f"{elem} in spot {spot}")
for elem in all_elems
for spot in all_spots
}
# only one spot for element
for elem in all_elems:
model.Add(sum(elements[elem, spot] for spot in all_spots) == 1)
for spot in all_spots:
# taking the element id as its size
sum_ = sum(elements[elem, spot] * elem for elem in all_elems)
model.Add(sum_ >= 0)
model.Add(sum_ <= 500)
solver.Solve(model)
for (elem, spot), boolean in elements.items():
if solver.Value(boolean):
print(boolean)
See:
https://github.com/google/or-tools/blob/stable/ortools/sat/samples/multiple_knapsack_sat.py
https://github.com/google/or-tools/blob/stable/ortools/sat/samples/binpacking_problem_sat.py
https://github.com/google/or-tools/blob/stable/examples/python/balance_group_sat.py#L102
In Apple Numbers the MOD function differs from Swift (in the German version it is REST.
In Numbers:
4,37937=MOD(−1,90373;6,2831)
versus
In swift 3:
let rem1: Double = -1.90373
let rem = rem1.truncatingRemainder(dividingBy: 6.28318530717959)
print(rem)
Prints: -1.90373
What I am doing wrong?
I found the solution:
let rem1: Double = -1.90373
let rem = rem1 - 6.28318530717959 * floor(rem1 / 6.28318530717959)
print(rem)
will do the same like Apples Numbers MOD is doing.
a % b performs the following and returns remainder
a = (b x some multiplier) + remainder
some multiplier is the largest number of multiples of b that will fit inside a.
e.g. some integer constant [0...]
The documentation provides the following as an example
Inserting -9 and 4 into the equation yields:
-9 = (4 x -2) + -1
giving a remainder value of -1.
The sign of b is ignored for negative values of b. This means that a
% b and a % -b always give the same answer.
36-> 6*6 (not 9*4)
40-> 5*8 (not 10*4)
35-> 7*5
etc
I'm guessing something like:
candidate = input.square_root.round_to_nearest_int;
while (true){
test = input/candidate;
if (test.is_integer) return;
else
candidate.decrement;
}
Your approach does work.
If n = ab then a <= sqrt(n) <= b, hence if a,b are chosen so that b-a is minimized, it follows that a is the largest divisor of n which is less than or equal to the square root. The only tweak I would make to your pseudocode is to check the remainder and see if it is zero, rather than checking if the quotient is an integer. Something like (in Python):
import math
def closestDivisors(n):
a = round(math.sqrt(n))
while n%a > 0: a -= 1
return a,n//a
For example,
>>> closestDivisors(36)
(6, 6)
>>> closestDivisors(40)
(5, 8)
>>> closestDivisors(1000003)
(1, 1000003)
(since the last input is prime).
Can anybody help me generate two different random numbers in two ranges? I've tried:
var a = Random.nextInt(S)
var b = Random.nextInt(K)
if (a == S || b == K){
a = S-1
b = K-1
}
(word,a,b)
But this generates some numbers that are not in the specified ranges.
From the docs on Random:
def nextInt(n: Int): Int
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
By the method contract, nextInt will always return a value from 0 to n - 1, so your condition a == S || b == K will always be false.