Last active
May 12, 2021 09:03
-
-
Save zzh1996/9686fdda15b69e4241cf8e4933cf653a to your computer and use it in GitHub Desktop.
solve_mod_mathematica
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from wolframclient.evaluation import WolframLanguageSession | |
from wolframclient.language import wl | |
def solve_mma(eqn, modulus): | |
if eqn.number_of_arguments() != 1: | |
raise NotImplementedError('Not univariate') | |
if eqn.is_polynomial(eqn.args()[0]): | |
poly = eqn | |
elif eqn.is_relational() and eqn.operator() is operator.eq: | |
poly = eqn.lhs() - eqn.rhs() | |
else: | |
raise NotImplementedError('Not polynomial or equation') | |
p = int(0) | |
for c, e in poly.coefficients(): | |
p = wl.Plus(p, wl.Times(int(c), wl.Power(wl.x, int(e)))) | |
session = WolframLanguageSession() | |
r = session.evaluate(wl.Quiet(wl.Solve(wl.Equal(p, int(0)), wl.x, Modulus=int(modulus)))) | |
ans = [] | |
for i in r: | |
ans.append(session.evaluate(wl.Quiet(wl.ReplaceAll(*i)(wl.x)))) | |
session.terminate() | |
return ans | |
# Usage: | |
# var('x') | |
# solve_mma(x ^ 2 == 1, 15) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment