Hi everyone:

I've made a little function for solving inequalities, it hasn't been
extensively tested but it works at least for solving both of Wester's
problems on inequalities and some my girlfriend had a few days ago.

Hope you find it useful.

Cheers.

------------------
Sirio Bolaños.
UNAM, México

--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to sage-devel@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/sage-devel
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

#!/usr/bin/env python

#function parameters are the inequality to solve and left and right endpoints tuple of the interval in which to search for a solution (consequence of the plot-dependant algorithm for finding all roots)

def isolve(ineq,(rleft,rright)):
    zeros = []
    roots = []
    solution = []
    #perhaps eps should also be a parameter?
    eps = 0.000000001
    
    try:
        op = ineq.__getitem__(1)
        lm = ineq.__getitem__(0)
        rm = ineq.__getitem__(2)
    except:
        raise ValueError, "trying to solve expression without operator"
    if op == operator.eq:
        raise ValueError, "trying to solve equation, please use solve() instead"
        
    f = lm - rm
    p = plot(f,(rleft,rright),plot_points=1000)
    
    for i in range(len(p[0])-1):
        if (p[0][i][1] > 0 and p[0][i+1][1] < 0) or (p[0][i][1] < 0 and p[0][i+1][1] > 0):
             zeros.append((p[0][i],p[0][i+1]))
             
    if len(zeros) is not 0:
        for i in range(len(zeros)):
            root = f.find_root(zeros[i][0][0],zeros[i][1][0])
            #quick fix to find_root providing inexact roots if integers
            if abs(floor(root)-root) < eps:
                root = floor(root)
            elif abs(ceil(root)-root) < eps:
                root = ceil(root)
            roots.append(root)
    else:
        raise ValueError, "inequality has no solution"
    #FIXME provide a way of specifying if RIF is open or closed interval depending on operator (<,<=,>,>=)    
    if len(roots) > 1:
        if bool(op(f(roots[0]-eps),0)) is True:
            solution.append(RIF((-infinity,roots[0])))
        for i in range(len(roots)-1):
            if bool(op(f(roots[i]+eps),0)) is True:
                solution.append(RIF((roots[i],roots[i+1])))
        if bool(op(f(roots[-1]+eps),0)) is True:
            solution.append(RIF((roots[-1],infinity)))
    else:
        if bool(op(f(roots[0]+eps),0)) is True:
            solution.append(RIF((roots[0],infinity)))
        else:
            solution.append(RIF((-infinity,roots[0])))
    return solution

Reply via email to