Reusable · From evidence to a Lean proof

Follow three proofs in Lean, from a triangle bound to a matrix certificate, and see how theorems can be combined to design specialized mathematical workflows.

Chapters
English transcript

How large can the sum be?

Choose a triangle and call its angles A, B, and C. Add the cosines of those three angles. How large can the sum be? The answer is three halves. An equilateral triangle reaches that value. To prove the bound for every triangle, we'll use a theorem from Reusable, a library of Lean proofs. The theorem gives us an identity that turns the inequality into two squares.

Find the theorem

Open the Reusable showcase. In the search box, enter Wolstenholme defect. This card is Wolstenholme's inequality, in defect form. The Lean statement shows the exact name and assumptions. The minimal import is the Geometry module. The provenance links you to the original theorem in the archive. The trust row lists the axioms Lean reports for this result.

Read the identity

The identity assumes the three angles add to pi. The weights x, y, and z can be any real numbers. Start with the sum of the squares of the weights, then subtract the weighted cosine expression. The theorem says this difference equals the sum of the two squares shown below. Each square is nonnegative, so the difference is nonnegative too. That gives us the weighted inequality. The identity does the trigonometric work. The angle sum matters. Drop that hypothesis and set every angle to zero and every weight to one. The claimed inequality becomes six at most three. Lean checks this counterexample.

Prove it in Lean

Here's the example from Recipe One of the guide, with its import. The example takes six real numbers and the angle sum as a hypothesis. have key applies the theorem to those inputs and puts the equality in the local context. The next command passes the nonnegativity of each square to Lean's nonlinear arithmetic tactic. Using the equality and those two facts, the tactic closes the goal.

Try x = y = z = 1

Now use one for each of the three weights. The right side is three, and the left side is twice the sum of the cosines. Divide both sides by two to recover our bound of three halves. The practice file checks this specialization in Lean. It applies the same theorem to three ones and closes the resulting goal. That is the first reuse pattern: a general identity becomes the particular result you need.

A certificate for three real roots

Now imagine you need to prove that this cubic has three distinct real roots. The graph suggests three crossings of the horizontal axis. How could we turn that picture into evidence Lean can use? R0011 asks for ordered sample points and alternating signs. At minus two, zero, one, and two, the exact values are minus one, one, minus one, and three. Notice the three open intervals. Each pair of consecutive values has strictly opposite signs, so each interval contains a root. The intervals are disjoint. This is why there are at least three distinct roots. We never need to compute the roots themselves. Watch what happens if we remove the constant term. One selected sample is now zero, so this particular certificate no longer meets the strict sign condition. Move that sample from zero to minus one. The four signs alternate again. Different witnesses can certify a different instance of the same problem.

Build a lemma on top of R0011

The practice file does something more general. It defines a lemma named three_real_roots, with four ordered points and three sign conditions. First supply the nonzero polynomial and the vector of sample points to R0011. Two obligations remain. The first obligation is that the vector is strictly increasing. Split into its three adjacent pairs and use the order hypotheses. The second is that the product of each adjacent pair of evaluations is negative. Each case is one of our sign hypotheses. We can now apply our lemma to the original cubic. Evaluating the polynomial at zero shows it is nonzero. Then norm_num checks the three inequalities between sample points and the three inequalities between products of evaluations. In the guide, Lean checks this chain from the generic theorem to the particular cubic. The plot helps us choose inputs for the proof.

Compose two matrix theorems

The next problem begins with a symmetric real matrix. We want a certificate that its quadratic form is a sum of squares. Here is a two by two example with twos on the diagonal and ones off the diagonal. Its characteristic polynomial is t squared minus four t plus three. The coefficients have signs plus, minus, plus. The determinant is three, so the two by two matrix has rank two. R0032 uses symmetry and the sign condition on the coefficients to give positive semidefiniteness. R0033 takes positive semidefiniteness and the rank. It gives a number of squares equal to the rank. For this matrix we can illustrate the result along the two diagonal directions. In ordinary coordinates, the displayed two squares expand to the original form. Recipe Four checks the general composition with symmetry, signs and rank as hypotheses. The companion file checks all three for this matrix and separately proves the displayed identity.

A desk for mathematical workflows

This suggests a way to build a specialized mathematical workflow. Begin with a concrete problem and state the guarantee you want before choosing a theorem. Suppose the requested output is a certificate that the quadratic form is a sum of exactly k squares. Find a theorem whose conclusion has that shape. Read the argument slots. Positive semidefiniteness can come from the preceding theorem. Symmetry, coefficient signs, and rank still need evidence. A calculation with exact coefficients can propose witnesses. The proof needs the exact facts accepted at the input of each theorem. The guide already contains the composed Lean term. A successful check of the abstract theorem confirms that the pieces fit under its hypotheses. To obtain a certificate for a specific matrix, you also need Lean proofs of those hypotheses for that matrix. Excovery already has a planner for tools with typed inputs and outputs. This view sketches a future interface for working at the level of theorem cards. It connects a problem, candidate theorems, open obligations, and the final Lean check. The guide already gives us examples to build from.

Start with the next case

Pick the next case you would like to prove. In the triangle, change the weights. In the cubic, change the sample points. For the matrix, start from the conclusion and work back to the exact coefficients and rank you can certify. A further design uses signs and a degree bound to certify all roots are real, then monicity and a valid index to apply Newton's inequalities. Use the guide and the theorem cards to follow each step to its Lean statement. The downloadable Lean files give you a working starting point.

Reusable · Del dato a la prueba en Lean

Recorre tres pruebas en Lean, desde una cota de un triángulo hasta un certificado matricial, y descubre cómo componer resultados para diseñar flujos matemáticos especializados.

Capítulos
Transcripción en español

¿Cuánto puede valer la suma?

Elige un triángulo y llama A, B y C a sus ángulos. Suma los cosenos de esos tres ángulos. ¿Hasta dónde puede llegar la suma? La respuesta es tres medios. El triángulo equilátero alcanza ese valor. Para demostrar la cota para cualquier triángulo, usaremos un teorema de Reusable, una biblioteca de pruebas en Lean. El teorema nos da una identidad que convierte la desigualdad en dos cuadrados.

Encuentra el teorema

Abre la vitrina de Reusable. En el buscador, escribe Wolstenholme defect. Es la ficha de la desigualdad de Wolstenholme, en forma de defecto. El enunciado en Lean indica el nombre exacto y las hipótesis. La importación mínima es el módulo de geometría. La procedencia te lleva al teorema original en el archivo. La fila de confianza enumera los axiomas que Lean declara para este resultado.

Lee la identidad

La identidad supone que los tres ángulos suman pi. Los pesos x, y, z pueden ser cualesquiera números reales. Parte de la suma de los cuadrados de los pesos y resta la expresión ponderada con cosenos. El teorema dice que esa diferencia es igual a la suma de los dos cuadrados que ves abajo. Cada cuadrado es no negativo, así que la diferencia también lo es. Así obtenemos la desigualdad ponderada. La identidad resuelve la parte trigonométrica. La suma de los ángulos importa. Quita esa hipótesis, pon los tres ángulos a cero y los tres pesos a uno. La desigualdad afirmaría que seis es menor o igual que tres. Lean comprueba este contraejemplo.

Demuéstralo en Lean

Aquí tienes el ejemplo de la primera receta de la guía, con su importación. El ejemplo toma seis números reales y la suma de los ángulos como hipótesis. La línea resaltada aplica el teorema a esos datos y guarda la igualdad en el contexto local. La instrucción siguiente da a la táctica de aritmética no lineal de Lean la no negatividad de cada cuadrado. Con la igualdad y esos dos datos, la táctica cierra la demostración.

Prueba x = y = z = 1

Ahora toma uno para cada uno de los tres pesos. A la derecha queda tres y a la izquierda queda el doble de la suma de los cosenos. Divide los dos lados entre dos y recuperas la cota de tres medios. El archivo de práctica comprueba esta especialización en Lean. Aplica el mismo teorema con los tres pesos iguales a uno y cierra el objetivo. Así usamos la biblioteca por primera vez: una identidad general se convierte en el resultado particular que necesitamos.

Un certificado de tres raíces reales

Ahora queremos demostrar que esta cúbica tiene tres raíces reales distintas. En la gráfica parecen verse tres cruces con el eje horizontal. ¿Cómo convertimos esa imagen en datos que Lean pueda usar? La ficha R0011 pide puntos ordenados y signos alternos. En menos dos, cero, uno y dos, los valores exactos son menos uno, uno, menos uno y tres. Fíjate en los tres intervalos abiertos. Cada par de valores consecutivos tiene signos estrictamente opuestos, así que cada intervalo contiene una raíz. Como los intervalos son disjuntos, hay al menos tres raíces distintas. Podemos probarlo sin calcular las raíces. Mira lo que pasa si quitamos el término constante. Una de las muestras vale cero y este certificado deja de cumplir la condición de signos estrictos. Cambia esa muestra de cero a menos uno. Los cuatro signos vuelven a alternar. Otros testigos permiten certificar otro caso del mismo problema.

Construye un lema sobre R0011

El archivo de práctica va un paso más allá. Define un lema para tres raíces reales, con cuatro puntos ordenados y tres condiciones de signo. Primero damos a la ficha R0011 el polinomio no nulo y el vector de puntos de evaluación. Quedan dos obligaciones. La primera es que los puntos del vector estén en orden estricto. Separamos los tres pares consecutivos y usamos las hipótesis de orden. La segunda es que el producto de cada par de evaluaciones consecutivas sea negativo. Cada caso corresponde a una de las hipótesis de signo. Ya podemos aplicar nuestro lema a la cúbica inicial. Al evaluar el polinomio en cero queda demostrado que el polinomio no es nulo. Después, la táctica norm_num comprueba las tres desigualdades entre los puntos y las tres desigualdades entre los productos de evaluaciones. Lean comprueba la cadena desde el teorema general hasta la cúbica concreta. La gráfica nos ayuda a elegir los datos de la prueba.

Encadena dos teoremas de matrices

El siguiente problema empieza con una matriz real simétrica. Queremos un certificado de que su forma cuadrática es una suma de cuadrados. Aquí hay una matriz dos por dos con doses en la diagonal y unos fuera de ella. Su polinomio característico es te al cuadrado menos cuatro te más tres. Los coeficientes tienen signos más, menos, más. El determinante vale tres, así que la matriz dos por dos tiene rango dos. La ficha R0032 usa la simetría y los signos de los coeficientes para obtener semidefinitud positiva. La ficha R0033 toma la semidefinitud positiva y el rango. Devuelve tantos cuadrados como indica el rango. En esta matriz podemos ilustrar el resultado a lo largo de sus direcciones diagonales. Al desarrollar los dos cuadrados de la pantalla se obtiene la forma original. La cuarta receta comprueba la composición general con hipótesis de simetría, signos y rango. El archivo complementario comprueba las tres para esta matriz y demuestra por separado la identidad explícita.

Una mesa para diseñar flujos matemáticos

Podemos llevar esta idea a una mesa para diseñar un flujo matemático especializado. Parte de un problema concreto y fija la garantía que necesitas. Supongamos que quieres un certificado de que una forma cuadrática es suma de exactamente k cuadrados. Busca un teorema cuya conclusión tenga esa forma. Mira qué argumentos necesita. La semidefinitud positiva puede venir del teorema anterior. Todavía hay que justificar la simetría, los signos y el rango. Un cálculo con coeficientes exactos puede proponer testigos. La prueba necesita los hechos exactos que exige cada uno de los teoremas. La guía incluye el término Lean compuesto. Al comprobar el teorema abstracto, Lean confirma que las piezas encajan con esas hipótesis. Para obtener un certificado de una matriz concreta también necesitas pruebas, en Lean, de que esa matriz cumple cada hipótesis. Excovery ya tiene un planificador de herramientas con entradas y salidas tipadas. Esta mesa es una propuesta de interfaz para trabajar con fichas de teoremas. Conecta el problema, los teoremas candidatos, las obligaciones abiertas y la comprobación final en Lean. Los ejemplos de la guía son el punto de partida.

Empieza por el siguiente caso

Elige el siguiente caso que quieres demostrar. En el triángulo, cambia los pesos. Para la cúbica, prueba otros puntos de evaluación. En la matriz, parte de la conclusión y vuelve a los coeficientes exactos y al rango que puedes certificar. Otro diseño usa signos y una cota de grado para certificar que todas las raíces son reales. Con un polinomio mónico y un índice válido podemos aplicar las desigualdades de Newton. Usa la guía y las fichas para seguir cada paso hasta su enunciado Lean. Los archivos Lean de la guía te dan un ejemplo que puedes ejecutar.