How to add two rational in agda?

 ̄綄美尐妖づ 提交于 2020-01-15 16:46:30

问题


How to add two rational.. I was trying this but this is not correct. As I am unable to prove that coprime part.

open import Data.Rational
open import Data.Integer
open import Data.Nat

_add_ : ℚ -> ℚ -> ℚ
x add y = (nx Data.Integer.* dy Data.Integer.+ dx Data.Integer.* ny) ÷
          (dx′ Data.Nat.* dy′)
  where
    nx = ℚ.numerator x
    dx = ℚ.denominator x
    dx′ = ℕ.suc (ℚ.denominator-1 x)

    ny = ℚ.numerator y
    dy = ℚ.denominator y
    dy′ = ℕ.suc (ℚ.denominator-1 y)

回答1:


You need to simplify (nx * dy + dx * ny) / (dx * dy) to ensure its numerator and denominator are coprimes.

The following code shows you the core of the solution by simplifying a pair of natural numbers x and suc y-1 (i.e. a non-zero y). Extending it to handle the signs of the numerator should be an easy exercise. The heavy lifting is done by Data.Nat.Coprimality.Bézout-coprime.

open import Data.Nat
open import Data.Nat.GCD
open import Data.Nat.Coprimality hiding (sym)
open import Relation.Binary.PropositionalEquality
open import Data.Product
open import Data.Nat.Divisibility
open import Data.Empty

record Simp (x : ℕ) (y : ℕ) : Set where
  constructor MkSimp
  field
    x′ y′ : ℕ
    eq-prf : x * y′ ≡ x′ * y
    coprime-prf : Coprime x′ y′

1+≢*0 : ∀ x y → suc x ≢ y * 0
1+≢*0 x zero ()
1+≢*0 x (suc y) = 1+≢*0 x y

simp : ∀ x y-1 → Simp x (suc y-1)
simp x y-1 with Bézout.lemma x (suc y-1)
simp x y-1 | Bézout.result 0 (GCD.is (_ , divides y′ y-eq) _) _ = ⊥-elim (1+≢*0 y-1 y′ y-eq)
simp x y-1 | Bézout.result (suc d-1) (GCD.is (divides x′ x-eq , divides y′ y-eq) _) bézout = MkSimp x′ y′ eq-prf (Bézout-coprime bézout′)
  where
    y = suc y-1
    d = suc d-1

    bézout′ : Bézout.Identity d (x′ * d) (y′ * d)
    bézout′ = subst₂ (Bézout.Identity d) x-eq y-eq bézout

    open Relation.Binary.PropositionalEquality.≡-Reasoning
    open import Data.Nat.Properties.Simple

    eq-prf : x * y′ ≡ x′ * y
    eq-prf = begin
      x * y′         ≡⟨ cong (λ z → z * y′) x-eq ⟩
      x′ * d * y′    ≡⟨ *-assoc x′ d y′ ⟩
      x′ * (d * y′)  ≡⟨ sym (cong (_*_ x′) (*-comm y′ d)) ⟩
      x′ * (y′ * d)  ≡⟨ sym (cong (_*_ x′) y-eq)  ⟩
      x′ * y         ∎


来源:https://stackoverflow.com/questions/31212459/how-to-add-two-rational-in-agda

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!