All pastes #35927 Raw Edit

Stuff

public php v1 · immutable
#35927 ·published 2006-01-05 23:07 UTC
rendered paste body
<?phpclass Monomial {	var $numeric_factor = 1;	var $vars = array();	// 5a^2, n_f = 5, vars = array('a' => 2);	function mul(Monomial $b, $is_div = false) {		$nf = $this->numeric_factor * $b->numeric_factor;		$nv = array();		foreach($this->vars as $var => $exp) {			if(isset($b->vars[$var])) {				if($is_div) {					$nv[$var] = $exp - $b->vars[$var];				} else {					$nv[$var] = $exp + $b->vars[$var];				}			}	else {				$nv[$var] = $exp;			}		}		foreach($b->vars as $var => $exp) {			if(!isset($nv[$var])) {				if($is_div) {					throw new Exception('Illegal monomial division');				} else {					$nv[$var] = $exp;				}			}		}		$this->numeric_factor = $nf;		$this->vars = $nv;	}	function mulf(Monomial $b, $is_div = false) {		$m = clone $this;		$m->mul($b, $is_div);		return $m;	}	function div(Monomial $b) {		$this->mul($b, true);	}	function divf(Monomial $b) {		return mulf($b, true);	}	function remove_var_1($res) {		$v = $res[1];		$n = $res[2];		if(!isset($this->vars[$v])) $this->vars[$v] = 0;		$this->vars[$v] += $n;	}	function remove_var_2($res) {		$this->remove_var_1(array(0, $res[0], 1));	}	function Monomial($str='') {		$str = preg_replace_callback('/([a-z])\^([0-9]+)/i', array($this, 'remove_var_1'), $str);		$str = preg_replace_callback('/[a-z]/i', array($this, 'remove_var_2'), $str);		$str = trim($str);		if(is_numeric($str)) {			$this->numeric_factor = (real) $str;		} else if($str == '') {			$this->numeric_factor = 1;		} else {			throw new Exception('Nonnumeric final string ' . $str);		}	}	function to_str() {		$str = (string) $this->numeric_factor;		foreach($this->vars as $v => $e) {			if($e == 1) {				$str .= $v;			} else {				$str .= "$v^$e";			}		}		return $str;	}}$x = new Monomial('7a^2b^3cd^4');echo "Original is:\n";echo $x->to_str() . "\n";$mul = new Monomial('14bc^2');echo "Multiply by:\n";echo $mul->to_str() . "\n";$x->mul($mul);echo "Final is:\n";echo $x->to_str() . "\n";?>