2way?
① i want to choice ...tGreaterThan element ----> n > 6.1875
②I can convert it to a string and use a regular expression.
preorder_traversal < Walking the Tree
https://docs.sympy.org/latest/tutorial/manipulation.html#walking-the-tree
i try
from sympy import *
var('n')
f=(99/16 < n) & (n < oo)
for arg in preorder_traversal(f):
print("#",arg,"____",type(arg))
# (n > 6.1875) & (n < oo) ____ And
# n < oo ____ <class 'sympy.core.relational.StrictLessThan'>
# n ____ <class 'sympy.core.symbol.Symbol'>
# oo ____ <class 'sympy.core.numbers.Infinity'>
# n > 6.1875 ____ <class 'sympy.core.relational.StrictGreaterThan'>
# n ____ <class 'sympy.core.symbol.Symbol'>
# 6.18750000000000 ____ <class 'sympy.core.numbers.Float'>
ref)
japanese only
https://ja.stackoverflow.com/questions/74249/sympy%E3%81%AE1%E5%A4%89%E6%95%B0%E4%B8%8D%E7%AD%89%E5%BC%8F-inequality-solvers-%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6%E6%95%99%E3%81%88%E3%81%A6%E4%B8%8B%E3%81%95%E3%81%84
I'm not really sure what you are asking for but if you declare n to be real (and therefore finite) then this will simplify automatically:
In [5]: n = symbols('n', real=True)
In [6]: f=(99/16 < n) & (n < oo)
In [7]: f
Out[7]: n > 6.1875
Related
Actually I want to express a set of constraints like this: A + B + C + D + E <= F,
A,B,C,D,E,F are all l*t matrices.
Unfortunately, I only do constraint construction by using “for” loops,like this:
'''
model.TN = pyo.Set(initialize = TN)
model.LN = pyo.Set(initialize = LN)
model.Pc = pyo.Var(model.GN, model.TN, domain = pyo.NonNegativeReals)
def branch_Cap1(t, l):
return sum(Tc[l, n] * model.Pc[n, t] for n in range(GenCount)) - sum(Tl[l, bus] * ldata[bus , t] for bus in range(loadCount)) <= Fmax[l]
def branch_Cap2(t, l):
return sum(Tc[l, n] * model.Pc[n, t] for n in range(GenCount)) - sum(Tl[l, bus] * ldata[bus , t] for bus in range(loadCount)) >= - Fmax[l]
model.branch_Cap1 = pyo.Constraint(model.TN, model.LN, rule = lambda model, t, l: branch_Cap1(t, l))
model.branch_Cap2 = pyo.Constraint(model.TN, model.LN, rule = lambda model, t, l: branch_Cap2(t, l))
'''
Can somebody help me?
thanks a lot.
Can I get a brief explanation why this proof effort fails?
In my studies I'm trying to recognize simple patterns in generated lists of integers.
The generator below produces a list of alternating 0s and 1s. I'd like to prove that items at even indexes are 0.
val evenb : nat -> bool
let rec evenb n =
match n with
| 0 -> true
| 1 -> false
| n -> evenb (n - 2)
val nth_item : ls: list nat {length ls > 0} -> n: nat {n < length ls} -> nat
let rec nth_item ls n =
match ls with
| [h] -> h
| h :: t -> if n = 0 then h else nth_item t (n - 1)
val gen_01 : lng: nat {lng >= 2 && evenb lng} -> ls: list nat {length ls = lng}
let rec gen_01 lng =
match lng with
| 2 -> [0; 1]
| _ -> [0; 1] # gen_01 (lng - 2)
let rec lemma_01 (lng: nat {lng >= 2 && evenb lng}) :
Lemma (forall (n: nat {n <= lng - 2 && evenb n}) . (nth_item (gen_01 lng) n) = 0) =
match lng with
| 2 -> ()
| _ -> lemma_01 (lng - 2)
FStar returns 'could not prove post-condition'.
I'd appreciate any help regarding the approach.
F* should also report a secondary error location pointing to the conjunct in the postcondition that was not provable---in this case, it's just the nth_item (gen_01 lng) n = 0 goal.
One way to diagnose this is to consider one branch of the proof at a time. E.g. if you add an admit(); in the second branch, then you'll see that the first branch is easily provable. So, what's going wrong is the inductive case. You don't have a strong enough induction hypothesis to prove the property you want.
Here's one proof of it ... there are probably many others.
First, I proved this:
let rec access_2n (l:nat{l >= 2 && evenb l}) (n:nat{2 * n < l})
: Lemma (ensures nth_item (gen_01 l) (2 * n) = 0)
= match n with
| 0 -> ()
| _ -> access_2n (l - 2) (n - 1)
Notice the induction on the pair l, n so that the length and the access index decrease together.
This is pretty much the property you wanted to prove, stated slightly differently. To massage it into the form you want, I did this:
First, a lemma to interpret evenb arithmetically:
[Edit: I added an open FStar.Mul to bring the * symbol into scope for multiplication]
open FStar.Mul
let rec evenb_is_even (n:nat{evenb n})
: Lemma (2 * (n / 2) = n)
= match n with
| 0 -> ()
| _ -> evenb_is_even (n - 2)
Then to prove something very like your lemma, but for an explicit n.
let lemma_01_aux (lng: nat {lng >= 2 && evenb lng}) (n:nat{n <= lng - 2 && evenb n})
: Lemma (nth_item (gen_01 lng) n = 0)
= access_2n lng (n / 2); evenb_is_even n
And finally to universally quantify over n using a library that turns lemmas into quantified postconditions.
let lemma_01 (lng: nat {lng >= 2 && evenb lng})
: Lemma (forall (n: nat {n <= lng - 2 && evenb n}) . (nth_item (gen_01 lng) n) = 0)
= FStar.Classical.forall_intro_2 lemma_01_aux
I have a Coq function that classifies prime numbers.
I exported it to Haskell and tested it; it works fine.
I want to rigorously prove it indeed classifies primes,
so I tried to prove the following theorem isPrimeCorrect:
(************)
(* helper'' *)
(************)
Fixpoint helper' (p m n : nat) : bool :=
match m with
| 0 => false
| 1 => false
| S m' => (orb ((mult m n) =? p) (helper' p m' n))
end.
(**********)
(* helper *)
(**********)
Fixpoint helper (p m : nat) : bool :=
match m with
| 0 => false
| S m' => (orb ((mult m m) =? p) (orb (helper' p m' m) (helper p m')))
end.
(***********)
(* isPrime *)
(***********)
Fixpoint isPrime (p : nat) : bool :=
match p with
| 0 => false
| 1 => false
| S p' => (negb (helper p p'))
end.
(***********)
(* divides *)
(***********)
Definition divides (n p : nat) : Prop :=
exists (m : nat), ((mult m n) = p).
(*********)
(* prime *)
(*********)
Definition prime (p : nat) : Prop :=
(p > 1) /\ (forall (n : nat), ((divides n p) -> ((n = 1) \/ (n = p)))).
(*****************************)
(* isPrime correctness proof *)
(*****************************)
Theorem isPrimeCorrect: forall (p : nat),
((isPrime p) = true) <-> (prime p).
I spent a good few hours on this theorem today with no actual progress.
Actually, I was a bit surprised how difficult it is since I previously
managed to prove pretty similar stuff. Any hints/clues how to proceed?
You must explicitely write lemmas for each of the helping functions, which state exactly what you think this function does for you. For instance, I tried to do this for your helper' function and I came up with the following lemma:
Require Import Arith Psatz.
(************)
(* helper'' *)
(************)
Fixpoint helper' (p m n : nat) : bool :=
match m with
| 0 => false
| 1 => false
| S m' => (orb ((mult m n) =? p) (helper' p m' n))
end.
Lemma helper'_correct :
forall p m n,
helper' p m n = true <-> exists k, (1 < k <= m /\ p = k * n).
Proof.
intros p; induction m as [ | m' IH]; intros n.
split;[discriminate | ].
intros [k [abs _]].
lia. (* Here the hypothesis abs has statement 1 <= k < 0
and lia recognizes that it is absurd. *)
destruct m' as [ | m''] eqn: E.
split;[discriminate | intros [k [abs _]]; lia].
change (helper' p (S (S m'')) n) with (orb ((mult (S (S m'')) n) =? p)
(helper' p (S m'') n)).
rewrite Bool.orb_true_iff.
split.
intros [it | later].
now exists (S (S m'')); split;[lia | symmetry; apply beq_nat_true ].
rewrite IH in later; destruct later as [k [k1 k2]].
exists k.
(* here hypothesis k1 states 1 < k <= S m''
k2 states p = k * n
and we need to prove 1 < k <= S (S m'') /\ p = k * n
lia can do that automatically. *)
lia.
intros [k [[k1 km] k2]].
apply le_lt_or_eq in km; rewrite or_comm in km; destruct km as [km | km].
now left; rewrite <- km; rewrite Nat.eqb_eq, k2.
right; apply lt_n_Sm_le in km.
change (helper' p (S m'') n = true); rewrite IH.
exists k.
lia.
Qed.
Obviously there should also be a way to link the helper function wih the divides predicate.
This question is about TLA+ using toolbox (https://github.com/tlaplus/tlaplus/releases)
I haven't been able to find any tag about it. Sorry about that. This is why I only tagged with Primes. If I am missing something please be kind to add better tags or create the missing ones.
Here is the issue
There is a well known function and algorithm for GCD. Here it is.
------------------ MODULE Euclid -------------------------------
EXTENDS Naturals, TLC
CONSTANT K
Divides(i,j) == \E k \in 0..j: j = i * k
IsGCD(i,j,k) ==
Divides(i,j)
/\ Divides(i,k)
/\ \A r \in 0..j \cup 0..k :
(Divides(r,j ) /\ Divides(r,k)) => Divides(r,i)
(* --algorithm EuclidSedgewick
{
variables m \in 1..K, n \in 1..m, u = m, v = n;
{
L1: while (u # 0) {
if (u < v) { u := v || v := u };
L2: u := u - v
};
assert IsGCD(v, m, n)
}
}
*)
This is a well known solution which is working.
I'm now trying to write a isPrime function using this one. But I think what I'm doing is wrong. I would like to know if you have an idea.
isPrime(nb) ==
\E k \in 2..nb: isGCD(nb,k,1) \/ isGCD(nb,k,nb)
Thanks
There are many way to express the notion that an integer is prime, however your attempt says that an integer N is prime if there exists some integer k in 2..N for which the gcd(k,n) = 1 or gcd(k,n) = n. This is easily seen to be incorrect, as 4 is clearly composite but gcd(3,4) = 1. And, of course, for every N prime or not, gcd(N, N) = N.
I'm not sure about the rules for TLA+, but I had a quick read of some documentation and here's my try at IsPrime
isPrime(nb) == \A k in 2..nb-1: ~Divides(k, nb)
or
isPrime(nb) == \A k in 1..nb: Divides(k, nb) => ( (k = 1) \/ (k=nb) )
or, if you really want to work IsGCD in there for some reason
isPrime(nb) == \A k in 1..nb: IsGCD(k, nb, d) => ( (d = 1) \/ (d = nb) )
or
isPrime(nb) == \A k in 2..nb-1: IsGCD(k, nb, d) => (d = 1)
I need to take a random sample without replacement (each element only occurring once in the sample) from a longer list. I'm using the code below, but now I'd like to know:
Is there a library function that does this?
How can I improve this code? (I'm a Haskell beginner, so this would be useful even if there is a library function).
The purpose of the sampling is to be able to generalize findings from analyzing the sample to the population.
import System.Random
-- | Take a random sample without replacement of size size from a list.
takeRandomSample :: Int -> Int -> [a] -> [a]
takeRandomSample seed size xs
| size < hi = subset xs rs
| otherwise = error "Sample size must be smaller than population."
where
rs = randomSample seed size lo hi
lo = 0
hi = length xs - 1
getOneRandomV g lo hi = randomR (lo, hi) g
rsHelper size lo hi g x acc
| x `notElem` acc && length acc < size = rsHelper size lo hi new_g new_x (x:acc)
| x `elem` acc && length acc < size = rsHelper size lo hi new_g new_x acc
| otherwise = acc
where (new_x, new_g) = getOneRandomV g lo hi
-- | Get a random sample without replacement of size size between lo and hi.
randomSample seed size lo hi = rsHelper size lo hi g x [] where
(x, g) = getOneRandomV (mkStdGen seed) lo hi
subset l = map (l !!)
Here's a quick 'back-of-the-envelope' implementation of what Daniel Fischer suggested in his comment, using my preferred PRNG (mwc-random):
{-# LANGUAGE BangPatterns #-}
module Sample (sample) where
import Control.Monad.Primitive
import Data.Foldable (toList)
import qualified Data.Sequence as Seq
import System.Random.MWC
sample :: PrimMonad m => [a] -> Int -> Gen (PrimState m) -> m [a]
sample ys size = go 0 (l - 1) (Seq.fromList ys) where
l = length ys
go !n !i xs g | n >= size = return $! (toList . Seq.drop (l - size)) xs
| otherwise = do
j <- uniformR (0, i) g
let toI = xs `Seq.index` j
toJ = xs `Seq.index` i
next = (Seq.update i toI . Seq.update j toJ) xs
go (n + 1) (i - 1) next g
{-# INLINE sample #-}
This is pretty much a (terse) functional rewrite of R's internal C version of sample() as it's called without replacement.
sample is just a wrapper over a recursive worker function that incrementally shuffles the population until the desired sample size is reached, returning only that many shuffled elements. Writing the function like this ensures that GHC can inline it.
It's easy to use:
*Main> create >>= sample [1..100] 10
[51,94,58,3,91,70,19,65,24,53]
A production version might want to use something like a mutable vector instead of Data.Sequence in order to cut down on time spent doing GC.
I think a standard way to do this is to keep a fixed-size buffer initialized with the first N elements, and for each i'th element, i >= N, do this:
Pick a random number, j, between 0 and i.
If j < N then replace the j'th element in the buffer with the current one.
You can prove correctness by induction:
This clearly generates a random sample (I assume order is irrelevant) if you only have N elements. Now suppose it's true up to the i'th element. This means that the probability of any element being in the buffer is N/(i+1) (I start counting at 0).
After picking the random number, the probability that the i+1'th element is in the buffer is N/(i+2) (j is between 0 and i+1, and N of those end up in the buffer). What about the others?
P(k'th element is in the buffer after processing the i+1'th) =
P(k'th element was in the buffer before)*P(k'th element is not replaced) =
N/(i+1) * (1-1/(i+2)) =
N/(i+2)
Here's some code that does it, in sample-size space, using the standard (slow) System.Random.
import Control.Monad (when)
import Data.Array
import Data.Array.ST
import System.Random (RandomGen, randomR)
sample :: RandomGen g => g -> Int -> [Int] -> [Int]
sample g size xs =
if size < length xs
then error "sample size must be >= input length"
else elems $ runSTArray $ do
arr <- newListArray (0, size-1) pre
loop arr g size post
where
(pre, post) = splitAt size xs
loop arr g i [] = return arr
loop arr g i (x:xt) = do
let (j, g') = randomR (0, i) g
when (j < size) $ writeArray arr j x
loop arr g' (i+1) xt