This commit is contained in:
Gatecraft 2016-07-12 22:26:54 +02:00
parent c3668828fc
commit 6c98f2c5d7
34 changed files with 3371 additions and 1863 deletions

View File

@ -2,5 +2,8 @@
<classpath> <classpath>
<classpathentry kind="src" path="src"/> <classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry combineaccessrules="false" kind="src" path="/New2DGame"/>
<classpathentry combineaccessrules="false" kind="src" path="/DrakeEngine2"/>
<classpathentry kind="lib" path="D:/Programmazione/Java/Progetti Eclipse/GatePack/libs/objenesis-2.4.jar"/>
<classpathentry kind="output" path="bin"/> <classpathentry kind="output" path="bin"/>
</classpath> </classpath>

1
.gitignore vendored
View File

@ -10,3 +10,4 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid* hs_err_pid*
/bin/

View File

@ -1,6 +1,8 @@
eclipse.preferences.version=1 eclipse.preferences.version=1
encoding//src/org/nevec/rjm/BigSurd.java=UTF-8 encoding//src/org/nevec/rjm/BigSurd.java=UTF-8
encoding//src/org/nevec/rjm/BigSurdVec.java=UTF-8 encoding//src/org/nevec/rjm/BigSurdVec.java=UTF-8
encoding//src/org/nevec/rjm/NumeroAvanzato.java=UTF-8
encoding//src/org/nevec/rjm/NumeroAvanzatoVec.java=UTF-8
encoding//src/org/warpgate/pi/calculator/Main.java=UTF-8 encoding//src/org/warpgate/pi/calculator/Main.java=UTF-8
encoding//src/org/warpgate/pi/calculator/Parentesi.java=UTF-8 encoding//src/org/warpgate/pi/calculator/Parentesi.java=UTF-8
encoding//src/org/warpgate/pi/calculator/Radice.java=UTF-8 encoding//src/org/warpgate/pi/calculator/Radice.java=UTF-8

88
out.txt
View File

@ -1,88 +0,0 @@
•Analyzing expression:((+35(2√7))+(9(2√13)))/21
•Added implicit multiplications:((35*(2√7))+(9*(2√13)))/21
•Subdivision in classes:
•Analyzing expression:(35*(2√7))+(9*(2√13))
•Added implicit multiplications:(35*(2√7))+(9*(2√13))
•Subdivision in classes:
•Analyzing expression:35*(2√7)
•Added implicit multiplications:35*(2√7)
•Subdivision in classes:
•Added variable to expression:35
•Added variable to expression:*
•Analyzing expression:2√7
•Subdivision in classes:
•Added variable to expression:2
•Added variable to expression:√
•Added variable to expression:7
•Finished the subdivision in classes.
•Pushing classes...
•Correcting classes:
•Set variable to expression:√
var1=2
var2=7
(result)=2√7
•Finished correcting classes.
•Result:2√7
•Added variable to expression:Parentesi
•Finished the subdivision in classes.
•Pushing classes...
•Correcting classes:
•Set variable to expression:*
var1=35
var2=2√7
(result)=35*(2√7)
•Finished correcting classes.
•Result:35*(2√7)
•Added variable to expression:Parentesi
•Added variable to expression:+
•Analyzing expression:9*(2√13)
•Added implicit multiplications:9*(2√13)
•Subdivision in classes:
•Added variable to expression:9
•Added variable to expression:*
•Analyzing expression:2√13
•Subdivision in classes:
•Added variable to expression:2
•Added variable to expression:√
•Added variable to expression:13
•Finished the subdivision in classes.
•Pushing classes...
•Correcting classes:
•Set variable to expression:√
var1=2
var2=13
(result)=2√13
•Finished correcting classes.
•Result:2√13
•Added variable to expression:Parentesi
•Finished the subdivision in classes.
•Pushing classes...
•Correcting classes:
•Set variable to expression:*
var1=9
var2=2√13
(result)=9*(2√13)
•Finished correcting classes.
•Result:9*(2√13)
•Added variable to expression:Parentesi
•Finished the subdivision in classes.
•Pushing classes...
•Correcting classes:
•Set variable to expression:+
var1=35*(2√7)
var2=9*(2√13)
(result)=35*(2√7)+9*(2√13)
•Finished correcting classes.
•Result:35*(2√7)+9*(2√13)
•Added variable to expression:Parentesi
•Added variable to expression:/
•Added variable to expression:21
•Finished the subdivision in classes.
•Pushing classes...
•Correcting classes:
•Set variable to expression:/
var1=35*(2√7)+9*(2√13)
var2=21
(result)=(35*(2√7)+9*(2√13))/21
•Finished correcting classes.
•Result:(35*(2√7)+9*(2√13))/21

View File

@ -3,6 +3,8 @@ package org.nevec.rjm ;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.Vector; import java.util.Vector;
import org.warpgate.pi.calculator.Errore;
/** Bernoulli numbers. /** Bernoulli numbers.
* @since 2006-06-25 * @since 2006-06-25
@ -44,8 +46,9 @@ public class Bernoulli
/** The Bernoulli number at the index provided. /** The Bernoulli number at the index provided.
* @param n the index, non-negative. * @param n the index, non-negative.
* @return the B_0=1 for n=0, B_1=-1/2 for n=1, B_2=1/6 for n=2 etc * @return the B_0=1 for n=0, B_1=-1/2 for n=1, B_2=1/6 for n=2 etc
* @throws Errore
*/ */
public Rational at(int n) public Rational at(int n) throws Errore
{ {
if ( n == 1) if ( n == 1)
return(new Rational(-1,2)) ; return(new Rational(-1,2)) ;
@ -67,7 +70,7 @@ public class Bernoulli
* @param n The index of the Bernoulli number. * @param n The index of the Bernoulli number.
* @return The Bernoulli number at n. * @return The Bernoulli number at n.
*/ */
private Rational doubleSum(int n) private Rational doubleSum(int n) throws Errore
{ {
Rational resul = Rational.ZERO ; Rational resul = Rational.ZERO ;
for(int k=0 ; k <= n ; k++) for(int k=0 ; k <= n ; k++)

View File

@ -5,6 +5,8 @@ import java.math.BigInteger;
import java.math.MathContext; import java.math.MathContext;
import java.security.ProviderException; import java.security.ProviderException;
import org.warpgate.pi.calculator.Errore;
/** BigDecimal special functions. /** BigDecimal special functions.
* <a href="http://arxiv.org/abs/0908.3030">A Java Math.BigDecimal Implementation of Core Mathematical Functions</a> * <a href="http://arxiv.org/abs/0908.3030">A Java Math.BigDecimal Implementation of Core Mathematical Functions</a>
@ -120,9 +122,10 @@ public class BigDecimalMath
/** Euler's constant. /** Euler's constant.
* @param mc The required precision of the result. * @param mc The required precision of the result.
* @return 3.14159... * @return 3.14159...
* @throws Errore
* @since 2009-05-29 * @since 2009-05-29
*/ */
static public BigDecimal pi(final MathContext mc) static public BigDecimal pi(final MathContext mc) throws Errore
{ {
/* look it up if possible */ /* look it up if possible */
if ( mc.getPrecision() < PI.precision() ) if ( mc.getPrecision() < PI.precision() )
@ -140,9 +143,10 @@ public class BigDecimalMath
/** Euler-Mascheroni constant. /** Euler-Mascheroni constant.
* @param mc The required precision of the result. * @param mc The required precision of the result.
* @return 0.577... * @return 0.577...
* @throws Errore
* @since 2009-08-13 * @since 2009-08-13
*/ */
static public BigDecimal gamma(MathContext mc) static public BigDecimal gamma(MathContext mc) throws Errore
{ {
/* look it up if possible */ /* look it up if possible */
if ( mc.getPrecision() < GAMMA.precision() ) if ( mc.getPrecision() < GAMMA.precision() )
@ -212,12 +216,11 @@ public class BigDecimalMath
* smaller than the precision requested. The relative correction is 1-x/s^2, * smaller than the precision requested. The relative correction is 1-x/s^2,
* (actually half of this, which we use for a little bit of additional protection). * (actually half of this, which we use for a little bit of additional protection).
*/ */
if ( Math.abs(BigDecimal.ONE.subtract(x.divide(s.pow(2,locmc),locmc)).doubleValue()) < eps) if ( Math.abs(BigDecimal.ONE.subtract(x.divide(s.pow(2,locmc),locmc)).doubleValue()) <= eps)
break ; break ;
s = s.add(x.divide(s,locmc)).divide(half,locmc) ; s = s.add(x.divide(s,locmc)).divide(half,locmc) ;
/* debugging /* debugging*/
* System.out.println("itr "+x.round(locmc).toString() + " " + s.round(locmc).toString()) ; System.out.println("itr "+x.round(locmc).toString() + " " + s.round(locmc).toString()) ;
*/
} }
return s ; return s ;
} /* BigDecimalMath.sqrt */ } /* BigDecimalMath.sqrt */
@ -559,8 +562,9 @@ public class BigDecimalMath
* @return ln(n). * @return ln(n).
* @since 2009-08-08 * @since 2009-08-08
* @author Richard J. Mathar * @author Richard J. Mathar
* @throws Errore
*/ */
static public BigDecimal log(int n, final MathContext mc) static public BigDecimal log(int n, final MathContext mc) throws Errore
{ {
/* the value is undefined if x is negative. /* the value is undefined if x is negative.
*/ */
@ -938,9 +942,10 @@ public class BigDecimalMath
/** Trigonometric sine. /** Trigonometric sine.
* @param x The argument in radians. * @param x The argument in radians.
* @return sin(x) in the range -1 to 1. * @return sin(x) in the range -1 to 1.
* @throws Errore
* @since 2009-06-01 * @since 2009-06-01
*/ */
static public BigDecimal sin(final BigDecimal x) static public BigDecimal sin(final BigDecimal x) throws Errore
{ {
if ( x.compareTo(BigDecimal.ZERO) < 0) if ( x.compareTo(BigDecimal.ZERO) < 0)
return sin(x.negate()).negate() ; return sin(x.negate()).negate() ;
@ -1024,9 +1029,10 @@ public class BigDecimalMath
/** Trigonometric cosine. /** Trigonometric cosine.
* @param x The argument in radians. * @param x The argument in radians.
* @return cos(x) in the range -1 to 1. * @return cos(x) in the range -1 to 1.
* @throws Errore
* @since 2009-06-01 * @since 2009-06-01
*/ */
static public BigDecimal cos(final BigDecimal x) static public BigDecimal cos(final BigDecimal x) throws Errore
{ {
if ( x.compareTo(BigDecimal.ZERO) < 0) if ( x.compareTo(BigDecimal.ZERO) < 0)
return cos(x.negate()); return cos(x.negate());
@ -1110,8 +1116,9 @@ public class BigDecimalMath
/** The trigonometric tangent. /** The trigonometric tangent.
* @param x the argument in radians. * @param x the argument in radians.
* @return the tan(x) * @return the tan(x)
* @throws Errore
*/ */
static public BigDecimal tan(final BigDecimal x) static public BigDecimal tan(final BigDecimal x) throws Errore
{ {
if ( x.compareTo(BigDecimal.ZERO) == 0 ) if ( x.compareTo(BigDecimal.ZERO) == 0 )
return BigDecimal.ZERO ; return BigDecimal.ZERO ;
@ -1176,9 +1183,10 @@ public class BigDecimalMath
/** The trigonometric co-tangent. /** The trigonometric co-tangent.
* @param x the argument in radians. * @param x the argument in radians.
* @return the cot(x) * @return the cot(x)
* @throws Errore
* @since 2009-07-31 * @since 2009-07-31
*/ */
static public BigDecimal cot(final BigDecimal x) static public BigDecimal cot(final BigDecimal x) throws Errore
{ {
if ( x.compareTo(BigDecimal.ZERO) == 0 ) if ( x.compareTo(BigDecimal.ZERO) == 0 )
{ {
@ -1240,8 +1248,9 @@ public class BigDecimalMath
/** The inverse trigonometric sine. /** The inverse trigonometric sine.
* @param x the argument. * @param x the argument.
* @return the arcsin(x) in radians. * @return the arcsin(x) in radians.
* @throws Errore
*/ */
static public BigDecimal asin(final BigDecimal x) static public BigDecimal asin(final BigDecimal x) throws Errore
{ {
if ( x.compareTo(BigDecimal.ONE) > 0 || x.compareTo(BigDecimal.ONE.negate()) < 0 ) if ( x.compareTo(BigDecimal.ONE) > 0 || x.compareTo(BigDecimal.ONE.negate()) < 0 )
{ {
@ -1346,9 +1355,10 @@ public class BigDecimalMath
/** The inverse trigonometric cosine. /** The inverse trigonometric cosine.
* @param x the argument. * @param x the argument.
* @return the arccos(x) in radians. * @return the arccos(x) in radians.
* @throws Errore
* @since 2009-09-29 * @since 2009-09-29
*/ */
static public BigDecimal acos(final BigDecimal x) static public BigDecimal acos(final BigDecimal x) throws Errore
{ {
/* Essentially forwarded to pi/2 - asin(x) /* Essentially forwarded to pi/2 - asin(x)
*/ */
@ -1374,9 +1384,10 @@ public class BigDecimalMath
/** The inverse trigonometric tangent. /** The inverse trigonometric tangent.
* @param x the argument. * @param x the argument.
* @return the principal value of arctan(x) in radians in the range -pi/2 to +pi/2. * @return the principal value of arctan(x) in radians in the range -pi/2 to +pi/2.
* @throws Errore
* @since 2009-08-03 * @since 2009-08-03
*/ */
static public BigDecimal atan(final BigDecimal x) static public BigDecimal atan(final BigDecimal x) throws Errore
{ {
if ( x.compareTo(BigDecimal.ZERO) < 0 ) if ( x.compareTo(BigDecimal.ZERO) < 0 )
{ {
@ -1467,9 +1478,10 @@ public class BigDecimalMath
* @param x The argument. * @param x The argument.
* @return The cosh(x) = (exp(x)+exp(-x))/2 . * @return The cosh(x) = (exp(x)+exp(-x))/2 .
* @author Richard J. Mathar * @author Richard J. Mathar
* @throws Errore
* @since 2009-08-19 * @since 2009-08-19
*/ */
static public BigDecimal cosh(final BigDecimal x) static public BigDecimal cosh(final BigDecimal x) throws Errore
{ {
if ( x.compareTo(BigDecimal.ZERO) < 0) if ( x.compareTo(BigDecimal.ZERO) < 0)
return cos(x.negate()); return cos(x.negate());
@ -1533,9 +1545,10 @@ public class BigDecimalMath
* @param x the argument. * @param x the argument.
* @return the sinh(x) = (exp(x)-exp(-x))/2 . * @return the sinh(x) = (exp(x)-exp(-x))/2 .
* @author Richard J. Mathar * @author Richard J. Mathar
* @throws Errore
* @since 2009-08-19 * @since 2009-08-19
*/ */
static public BigDecimal sinh(final BigDecimal x) static public BigDecimal sinh(final BigDecimal x) throws Errore
{ {
if ( x.compareTo(BigDecimal.ZERO) < 0) if ( x.compareTo(BigDecimal.ZERO) < 0)
return sinh(x.negate()).negate() ; return sinh(x.negate()).negate() ;
@ -1688,9 +1701,10 @@ public class BigDecimalMath
/** The Gamma function. /** The Gamma function.
* @param x The argument. * @param x The argument.
* @return Gamma(x). * @return Gamma(x).
* @throws Errore
* @since 2009-08-06 * @since 2009-08-06
*/ */
static public BigDecimal Gamma(final BigDecimal x) static public BigDecimal Gamma(final BigDecimal x) throws Errore
{ {
/* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33 /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33
*/ */
@ -1778,9 +1792,10 @@ public class BigDecimalMath
* @param q The argument. * @param q The argument.
* @param mc The required accuracy in the result. * @param mc The required accuracy in the result.
* @return Gamma(x). * @return Gamma(x).
* @throws Errore
* @since 2010-05-26 * @since 2010-05-26
*/ */
static public BigDecimal Gamma(final Rational q, final MathContext mc) static public BigDecimal Gamma(final Rational q, final MathContext mc) throws Errore
{ {
if ( q.isBigInteger() ) if ( q.isBigInteger() )
{ {
@ -1878,9 +1893,10 @@ public class BigDecimalMath
/** Reduce value to the interval [0,2*Pi]. /** Reduce value to the interval [0,2*Pi].
* @param x the original value * @param x the original value
* @return the value modulo 2*pi in the interval from 0 to 2*pi. * @return the value modulo 2*pi in the interval from 0 to 2*pi.
* @throws Errore
* @since 2009-06-01 * @since 2009-06-01
*/ */
static public BigDecimal mod2pi(BigDecimal x) static public BigDecimal mod2pi(BigDecimal x) throws Errore
{ {
/* write x= 2*pi*k+r with the precision in r defined by the precision of x and not /* write x= 2*pi*k+r with the precision in r defined by the precision of x and not
* compromised by the precision of 2*pi, so the ulp of 2*pi*k should match the ulp of x. * compromised by the precision of 2*pi, so the ulp of 2*pi*k should match the ulp of x.
@ -1914,9 +1930,10 @@ public class BigDecimalMath
/** Reduce value to the interval [-Pi/2,Pi/2]. /** Reduce value to the interval [-Pi/2,Pi/2].
* @param x The original value * @param x The original value
* @return The value modulo pi, shifted to the interval from -Pi/2 to Pi/2. * @return The value modulo pi, shifted to the interval from -Pi/2 to Pi/2.
* @throws Errore
* @since 2009-07-31 * @since 2009-07-31
*/ */
static public BigDecimal modpi(BigDecimal x) static public BigDecimal modpi(BigDecimal x) throws Errore
{ {
/* write x= pi*k+r with the precision in r defined by the precision of x and not /* write x= pi*k+r with the precision in r defined by the precision of x and not
* compromised by the precision of pi, so the ulp of pi*k should match the ulp of x. * compromised by the precision of pi, so the ulp of pi*k should match the ulp of x.
@ -1954,9 +1971,10 @@ public class BigDecimalMath
* @param n The positive integer argument. * @param n The positive integer argument.
* @param mc Specification of the accuracy of the result. * @param mc Specification of the accuracy of the result.
* @return zeta(n). * @return zeta(n).
* @throws Errore
* @since 2009-08-05 * @since 2009-08-05
*/ */
static public BigDecimal zeta(final int n, final MathContext mc) static public BigDecimal zeta(final int n, final MathContext mc) throws Errore
{ {
if( n <= 0 ) if( n <= 0 )
throw new ProviderException("Not implemented: zeta at negative argument "+n) ; throw new ProviderException("Not implemented: zeta at negative argument "+n) ;
@ -2117,9 +2135,10 @@ public class BigDecimalMath
/** Riemann zeta function. /** Riemann zeta function.
* @param n The positive integer argument. * @param n The positive integer argument.
* @return zeta(n)-1. * @return zeta(n)-1.
* @throws Errore
* @since 2009-08-20 * @since 2009-08-20
*/ */
static public double zeta1(final int n) static public double zeta1(final int n) throws Errore
{ {
/* precomputed static table in double precision /* precomputed static table in double precision
*/ */
@ -2208,9 +2227,10 @@ public class BigDecimalMath
* @param x The main argument. * @param x The main argument.
* @return psi(x). * @return psi(x).
* The error is sometimes up to 10 ulp, where AS 6.3.15 suffers from cancellation of digits and psi=0 * The error is sometimes up to 10 ulp, where AS 6.3.15 suffers from cancellation of digits and psi=0
* @throws Errore
* @since 2009-08-26 * @since 2009-08-26
*/ */
static public double psi(final double x) static public double psi(final double x) throws Errore
{ {
/* the single positive zero of psi(x) /* the single positive zero of psi(x)
*/ */
@ -2280,10 +2300,11 @@ public class BigDecimalMath
* @param a The vector of 8 integer arguments * @param a The vector of 8 integer arguments
* @param mc Specification of the accuracy of the result * @param mc Specification of the accuracy of the result
* @return S_(n,p)(a) * @return S_(n,p)(a)
* @throws Errore
* @since 2009-08-09 * @since 2009-08-09
* @see <a href="http://arxiv.org/abs/math/9803067">arXiv:math/9803067</a> * @see <a href="http://arxiv.org/abs/math/9803067">arXiv:math/9803067</a>
*/ */
static protected BigDecimal broadhurstBBP(final int n, final int p, final int a[], MathContext mc) static protected BigDecimal broadhurstBBP(final int n, final int p, final int a[], MathContext mc) throws Errore
{ {
/* Explore the actual magnitude of the result first with a quick estimate. /* Explore the actual magnitude of the result first with a quick estimate.
*/ */

View File

@ -3,6 +3,8 @@ package org.nevec.rjm ;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.Vector; import java.util.Vector;
import org.warpgate.pi.calculator.Errore;
/** BigInteger special functions and Number theory. /** BigInteger special functions and Number theory.
* @since 2009-08-06 * @since 2009-08-06
@ -365,8 +367,9 @@ public class BigIntegerMath
* @return The vector of x in A*x=rhs. * @return The vector of x in A*x=rhs.
* @since 2010-08-28 * @since 2010-08-28
* @author Richard J. Mathar * @author Richard J. Mathar
* @throws Errore
*/ */
static public Rational[] solve(final BigInteger[][]A, final BigInteger[] rhs) throws ArithmeticException static public Rational[] solve(final BigInteger[][]A, final BigInteger[] rhs) throws ArithmeticException, Errore
{ {
final int rL = A.length ; final int rL = A.length ;
@ -483,9 +486,10 @@ public class BigIntegerMath
* @return t(n,k) * @return t(n,k)
* @since 2009-08-06 * @since 2009-08-06
* @author Richard J. Mathar * @author Richard J. Mathar
* @throws Errore
* @see <a href="http://dx.doi.org/10.1080/01630568908816313">P. L. Butzer et al, Num. Funct. Anal. Opt. 10 (5)( 1989) 419-488</a> * @see <a href="http://dx.doi.org/10.1080/01630568908816313">P. L. Butzer et al, Num. Funct. Anal. Opt. 10 (5)( 1989) 419-488</a>
*/ */
static public Rational centrlFactNumt(int n,int k) static public Rational centrlFactNumt(int n,int k) throws Errore
{ {
if ( k > n || k < 0 || ( k % 2 ) != (n % 2) ) if ( k > n || k < 0 || ( k % 2 ) != (n % 2) )
return Rational.ZERO ; return Rational.ZERO ;

View File

@ -5,6 +5,8 @@ import java.math.BigInteger;
import java.util.Scanner; import java.util.Scanner;
import java.util.Vector; import java.util.Vector;
import org.warpgate.pi.calculator.Errore;
/** Polynomial with integer coefficients. /** Polynomial with integer coefficients.
* Alternatively to be interpreted as a sequence which has the polynomial as an (approximate) * Alternatively to be interpreted as a sequence which has the polynomial as an (approximate)
* generating function. * generating function.
@ -519,9 +521,10 @@ public class BigIntegerPoly implements Cloneable
* @return A (potentially empty) vector of factors, without multiplicity. * @return A (potentially empty) vector of factors, without multiplicity.
* Only factors with non-zero absolute coefficient are generated. * Only factors with non-zero absolute coefficient are generated.
* This means the factors are of the form x^2+a*x+b=0 with nonzero b. * This means the factors are of the form x^2+a*x+b=0 with nonzero b.
* @throws Errore
* @since 2012-03-01 * @since 2012-03-01
*/ */
protected Vector<BigIntegerPoly> i2roots() protected Vector<BigIntegerPoly> i2roots() throws Errore
{ {
/* The vector of the factors to be returned /* The vector of the factors to be returned
*/ */
@ -605,9 +608,10 @@ public class BigIntegerPoly implements Cloneable
/** Factorization into integer polynomials. /** Factorization into integer polynomials.
* The current factorization detects only factors which are polynomials of order up to 2. * The current factorization detects only factors which are polynomials of order up to 2.
* @return The vector of factors. Factors with higher multiplicity are represented by repetition. * @return The vector of factors. Factors with higher multiplicity are represented by repetition.
* @throws Errore
* @since 2012-03-01 * @since 2012-03-01
*/ */
public Vector<BigIntegerPoly> ifactor() public Vector<BigIntegerPoly> ifactor() throws Errore
{ {
/* this ought be entirely rewritten in terms of the LLL algorithm /* this ought be entirely rewritten in terms of the LLL algorithm
*/ */

View File

@ -5,6 +5,7 @@ import java.math.BigInteger;
import java.math.MathContext; import java.math.MathContext;
import java.security.ProviderException; import java.security.ProviderException;
import org.warpgate.pi.calculator.Errore;
import org.warpgate.pi.calculator.Utils; import org.warpgate.pi.calculator.Utils;
/** Square roots on the real line. /** Square roots on the real line.
@ -56,8 +57,12 @@ public class BigSurd implements Cloneable, Comparable<BigSurd>
if ( b.signum() < 0 ) if ( b.signum() < 0 )
throw new ProviderException("Not implemented: imaginary surds") ; throw new ProviderException("Not implemented: imaginary surds") ;
this.disc = b ; this.disc = b ;
try {
normalize() ; normalize() ;
normalizeG() ; normalizeG() ;
} catch (Errore e) {
e.printStackTrace();
}
} }
/** ctor given the numerator and denominator of the root. /** ctor given the numerator and denominator of the root.
@ -175,9 +180,10 @@ public class BigSurd implements Cloneable, Comparable<BigSurd>
/** Divide by another square root. /** Divide by another square root.
* @param val A second number of this type. * @param val A second number of this type.
* @return The value of this/val * @return The value of this/val
* @throws Errore
* @since 2011-02-12 * @since 2011-02-12
*/ */
public BigSurd divide(final BigSurd val) public BigSurd divide(final BigSurd val) throws Errore
{ {
if( val.signum() == 0 ) if( val.signum() == 0 )
throw new ArithmeticException("Dividing "+ toFancyString() + " through zero.") ; throw new ArithmeticException("Dividing "+ toFancyString() + " through zero.") ;
@ -218,9 +224,10 @@ public class BigSurd implements Cloneable, Comparable<BigSurd>
/** Divide by an integer. /** Divide by an integer.
* @param val a second number. * @param val a second number.
* @return the value of this/val * @return the value of this/val
* @throws Errore
* @since 2011-02-12 * @since 2011-02-12
*/ */
public BigSurd divide(final BigInteger val) public BigSurd divide(final BigInteger val) throws Errore
{ {
if( val.signum() == 0 ) if( val.signum() == 0 )
throw new ArithmeticException("Dividing "+ toFancyString() + " through zero.") ; throw new ArithmeticException("Dividing "+ toFancyString() + " through zero.") ;
@ -230,9 +237,10 @@ public class BigSurd implements Cloneable, Comparable<BigSurd>
/** Divide by an integer. /** Divide by an integer.
* @param val A second number. * @param val A second number.
* @return The value of this/val * @return The value of this/val
* @throws Errore
* @since 2011-02-12 * @since 2011-02-12
*/ */
public BigSurd divide(int val) public BigSurd divide(int val) throws Errore
{ {
if( val == 0 ) if( val == 0 )
throw new ArithmeticException("Dividing "+ toFancyString() + " through zero.") ; throw new ArithmeticException("Dividing "+ toFancyString() + " through zero.") ;
@ -384,9 +392,10 @@ System.out.println("dv sq " + res) ;
} /* BigSurd.signum */ } /* BigSurd.signum */
/** Normalize to squarefree discriminant. /** Normalize to squarefree discriminant.
* @throws Errore
* @since 2011-02-12 * @since 2011-02-12
*/ */
protected void normalize() protected void normalize() throws Errore
{ {
/* Move squares out of the numerator and denominator of the discriminant /* Move squares out of the numerator and denominator of the discriminant
*/ */
@ -418,9 +427,10 @@ System.out.println("dv sq " + res) ;
} /* BigSurd.normalize */ } /* BigSurd.normalize */
/** Normalize to coprime numerator and denominator in prefactor and discriminant /** Normalize to coprime numerator and denominator in prefactor and discriminant
* @throws Errore
* @since 2011-02-12 * @since 2011-02-12
*/ */
protected void normalizeG() protected void normalizeG() throws Errore
{ {
/* Is there a common factor between the numerator of the prefactor /* Is there a common factor between the numerator of the prefactor
* and the denominator of the discriminant ? * and the denominator of the discriminant ?

View File

@ -5,6 +5,7 @@ import java.math.BigInteger;
import java.math.MathContext; import java.math.MathContext;
import java.util.Vector; import java.util.Vector;
import org.warpgate.pi.calculator.Errore;
import org.warpgate.pi.calculator.Utils; import org.warpgate.pi.calculator.Utils;
/** /**
@ -66,16 +67,22 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
terms = new Vector<BigSurd>(2); terms = new Vector<BigSurd>(2);
terms.add(a); terms.add(a);
terms.add(b); terms.add(b);
try {
normalize(); normalize();
} catch (Errore e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /* ctor */ } /* ctor */
/** /**
* Combine terms that can be written as a single surd. This unites for * Combine terms that can be written as a single surd. This unites for
* example the terms sqrt(90) and sqrt(10) to 4*sqrt(10). * example the terms sqrt(90) and sqrt(10) to 4*sqrt(10).
* @throws Errore
* *
* @since 2012-02-15 * @since 2012-02-15
*/ */
protected void normalize() { protected void normalize() throws Errore {
/* /*
* nothing to be done if at most one term * nothing to be done if at most one term
*/ */
@ -135,8 +142,15 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
* @since 2012-02-15 * @since 2012-02-15
*/ */
public int compareTo(BigSurdVec oth) { public int compareTo(BigSurdVec oth) {
final BigSurdVec diff = this.subtract(oth); BigSurdVec diff;
try {
diff = this.subtract(oth);
return diff.signum(); return diff.signum();
} catch (Errore e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
} /* compareTo */ } /* compareTo */
/** /**
@ -144,9 +158,10 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
* equal to or larger than zero. * equal to or larger than zero.
* *
* @return 0 or +-1. * @return 0 or +-1.
* @throws Errore
* @since 2012-02-15 * @since 2012-02-15
*/ */
public int signum() { public int signum() throws Errore {
/* /*
* the case of zero is unique, because no (reduced) vector of surds * the case of zero is unique, because no (reduced) vector of surds
* other than the one element 0 itself can add/subtract to zero. * other than the one element 0 itself can add/subtract to zero.
@ -289,8 +304,9 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
* @param val * @param val
* The value to be added to this. * The value to be added to this.
* @return The new value representing this+val. * @return The new value representing this+val.
* @throws Errore
*/ */
public BigSurdVec add(final BigSurdVec val) { public BigSurdVec add(final BigSurdVec val) throws Errore {
BigSurdVec sum = new BigSurdVec(); BigSurdVec sum = new BigSurdVec();
/* /*
* concatenate the vectors and eliminate common overlaps * concatenate the vectors and eliminate common overlaps
@ -315,8 +331,9 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
* @param val * @param val
* The value to be added to this. * The value to be added to this.
* @return The new value representing this+val. * @return The new value representing this+val.
* @throws Errore
*/ */
public BigSurdVec add(final BigSurd val) { public BigSurdVec add(final BigSurd val) throws Errore {
BigSurdVec sum = new BigSurdVec(); BigSurdVec sum = new BigSurdVec();
/* /*
* concatenate the vectors and eliminate common overlaps * concatenate the vectors and eliminate common overlaps
@ -333,8 +350,9 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
* @param val * @param val
* The value to be subtracted from this. * The value to be subtracted from this.
* @return The new value representing this-val. * @return The new value representing this-val.
* @throws Errore
*/ */
public BigSurdVec subtract(final BigSurdVec val) { public BigSurdVec subtract(final BigSurdVec val) throws Errore {
BigSurdVec sum = new BigSurdVec(); BigSurdVec sum = new BigSurdVec();
/* /*
* concatenate the vectors and eliminate common overlaps * concatenate the vectors and eliminate common overlaps
@ -352,8 +370,9 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
* @param val * @param val
* The value to be subtracted from this. * The value to be subtracted from this.
* @return The new value representing this-val. * @return The new value representing this-val.
* @throws Errore
*/ */
public BigSurdVec subtract(final BigSurd val) { public BigSurdVec subtract(final BigSurd val) throws Errore {
BigSurdVec sum = new BigSurdVec(); BigSurdVec sum = new BigSurdVec();
/* /*
* concatenate the vectors and eliminate common overlaps * concatenate the vectors and eliminate common overlaps
@ -388,9 +407,10 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
* Compute the square. * Compute the square.
* *
* @return this value squared. * @return this value squared.
* @throws Errore
* @since 2012-02-15 * @since 2012-02-15
*/ */
public BigSurdVec sqr() { public BigSurdVec sqr() throws Errore {
/* /*
* Binomial expansion. First the sum of the terms squared, then 2 times * Binomial expansion. First the sum of the terms squared, then 2 times
* the mixed products. * the mixed products.
@ -411,9 +431,10 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
* @param val * @param val
* a second number of this type. * a second number of this type.
* @return the product of this with the val. * @return the product of this with the val.
* @throws Errore
* @since 2011-02-12 * @since 2011-02-12
*/ */
public BigSurdVec multiply(final BigSurd val) { public BigSurdVec multiply(final BigSurd val) throws Errore {
BigSurdVec resul = new BigSurdVec(); BigSurdVec resul = new BigSurdVec();
for (BigSurd s : terms) for (BigSurd s : terms)
resul.terms.add(s.multiply(val)); resul.terms.add(s.multiply(val));
@ -421,7 +442,7 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
return resul; return resul;
} /* multiply */ } /* multiply */
public BigSurdVec multiply(final BigSurdVec val) { public BigSurdVec multiply(final BigSurdVec val) throws Errore {
BigSurdVec resul = new BigSurdVec(); BigSurdVec resul = new BigSurdVec();
for (BigSurd s : terms) { for (BigSurd s : terms) {
resul.terms.add(s); resul.terms.add(s);
@ -432,7 +453,7 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
return resul; return resul;
} /* multiply */ } /* multiply */
public BigSurdVec divide(final BigSurd val) { public BigSurdVec divide(final BigSurd val) throws Errore {
BigSurdVec resul = new BigSurdVec(); BigSurdVec resul = new BigSurdVec();
for (BigSurd s : terms) for (BigSurd s : terms)
resul.terms.add(s.divide(val)); resul.terms.add(s.divide(val));
@ -440,7 +461,7 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
return resul; return resul;
} /* multiply */ } /* multiply */
public BigSurdVec divide(final BigSurdVec val) { public BigSurdVec divide(final BigSurdVec val) throws Errore {
BigSurdVec resul = new BigSurdVec(); BigSurdVec resul = new BigSurdVec();
resul.terms = terms; resul.terms = terms;
for (BigSurd s : val.terms) { for (BigSurd s : val.terms) {
@ -576,16 +597,16 @@ public class BigSurdVec implements Comparable<BigSurdVec> {
if (numerator.compareTo(BigInteger.ONE) != 0) { if (numerator.compareTo(BigInteger.ONE) != 0) {
s += numerator.toString(); s += numerator.toString();
s += "*"; s += "*";
s += "("; //s += "("; Radice quadrata. non servono le parentesi.
} }
s += "2√"; s += "";
if (bs.disc.isInteger()) { if (bs.disc.isInteger()) {
s += bs.disc.toString(); s += bs.disc.toString();
} else { } else {
s += "("+bs.disc.toString()+")"; s += "("+bs.disc.toString()+")";
} }
if (numerator.compareTo(BigInteger.ONE) != 0) { if (numerator.compareTo(BigInteger.ONE) != 0) {
s += ")"; //s += ")"; Radice quadrata. non servono le parentesi.
} }
} }
} }

View File

@ -4,6 +4,8 @@ import java.math.BigInteger;
import java.util.Collections; import java.util.Collections;
import java.util.Vector; import java.util.Vector;
import org.warpgate.pi.calculator.Errore;
/** Factored integers. /** Factored integers.
* This class contains a non-negative integer with the prime factor decomposition attached. * This class contains a non-negative integer with the prime factor decomposition attached.
* @since 2006-08-14 * @since 2006-08-14
@ -423,9 +425,10 @@ public class Ifactor implements Cloneable, Comparable<Ifactor>
* @return n^(1/r). * @return n^(1/r).
* The return value falls into the Ifactor class if r is positive, but if r is negative * The return value falls into the Ifactor class if r is positive, but if r is negative
* a Rational type is needed. * a Rational type is needed.
* @throws Errore
* @since 2009-05-18 * @since 2009-05-18
*/ */
public Rational root(final int r) throws ArithmeticException public Rational root(final int r) throws ArithmeticException, Errore
{ {
if ( r == 0 ) if ( r == 0 )
throw new ArithmeticException("Cannot pull zeroth root of "+ toString()) ; throw new ArithmeticException("Cannot pull zeroth root of "+ toString()) ;

View File

@ -7,6 +7,8 @@ import java.util.Random;
import java.util.Scanner; import java.util.Scanner;
import java.util.Vector; import java.util.Vector;
import org.warpgate.pi.calculator.Errore;
/** A one-parameter polynomial with rational coefficients. /** A one-parameter polynomial with rational coefficients.
* Alternatively to be interpreted as a sequence which has the polynomial as an (approximate) * Alternatively to be interpreted as a sequence which has the polynomial as an (approximate)
* generating function. * generating function.
@ -61,9 +63,10 @@ class RatPoly
* @param A the list of values in the numerator of AFB * @param A the list of values in the numerator of AFB
* @param B the list of values in the denominator of AFB * @param B the list of values in the denominator of AFB
* @param nmax the order of the truncated polynomial representation * @param nmax the order of the truncated polynomial representation
* @throws Errore
* @since 2008-11-13 * @since 2008-11-13
*/ */
public RatPoly(final Vector<BigInteger> A, final Vector<BigInteger> B, int nmax) public RatPoly(final Vector<BigInteger> A, final Vector<BigInteger> B, int nmax) throws Errore
{ {
/* To allow common initialization with the signature below, /* To allow common initialization with the signature below,
* the main body is assembled in a separate function. * the main body is assembled in a separate function.
@ -77,9 +80,10 @@ class RatPoly
* At least one of these values must be a negative integer, which implicitly determines * At least one of these values must be a negative integer, which implicitly determines
* the order of the new polynomial. * the order of the new polynomial.
* @param B the list of values in the denominator of AFB * @param B the list of values in the denominator of AFB
* @throws Errore
* @since 2009-08-05 * @since 2009-08-05
*/ */
public RatPoly(final Vector<BigInteger> A, final Vector<BigInteger> B) public RatPoly(final Vector<BigInteger> A, final Vector<BigInteger> B) throws Errore
{ {
BigInteger Nmax = BigInteger.ONE.negate() ; BigInteger Nmax = BigInteger.ONE.negate() ;
for(int j=0; j < A.size() ; j++) for(int j=0; j < A.size() ; j++)
@ -103,9 +107,10 @@ class RatPoly
* @param A the list of values in the numerator of AFB * @param A the list of values in the numerator of AFB
* @param B the list of values in the denominator of AFB * @param B the list of values in the denominator of AFB
* @param nmax the order of the truncated polynomial representation * @param nmax the order of the truncated polynomial representation
* @throws Errore
* @since 2008-11-13 * @since 2008-11-13
*/ */
protected void init(final Vector<BigInteger> A, final Vector<BigInteger> B, int nmax) protected void init(final Vector<BigInteger> A, final Vector<BigInteger> B, int nmax) throws Errore
{ {
a = new Vector<Rational>() ; a = new Vector<Rational>() ;
Factorial f=new Factorial() ; Factorial f=new Factorial() ;
@ -370,9 +375,10 @@ class RatPoly
* term that remains undetermined based on the current number of coefficients. * term that remains undetermined based on the current number of coefficients.
* @param r the exponent of the power * @param r the exponent of the power
* @return This^r . * @return This^r .
* @throws Errore
* @since 2009-05-18 * @since 2009-05-18
*/ */
public RatPoly pow(final Rational r) throws ArithmeticException public RatPoly pow(final Rational r) throws ArithmeticException, Errore
{ {
/* split (a0+a1*x+a2*x^2+...)^r = a0^r*(1+a1/a0*r+a2/a0*r^2+..)^r /* split (a0+a1*x+a2*x^2+...)^r = a0^r*(1+a1/a0*r+a2/a0*r^2+..)^r
*/ */
@ -443,9 +449,10 @@ class RatPoly
/** Divide by a constant. /** Divide by a constant.
* @param val the constant through which the coefficients will be divided. * @param val the constant through which the coefficients will be divided.
* @return the Taylor expansion of this/val . * @return the Taylor expansion of this/val .
* @throws Errore
* @since 2009-05-18 * @since 2009-05-18
*/ */
public RatPoly divide(final Rational val) public RatPoly divide(final Rational val) throws Errore
{ {
if ( val.compareTo(Rational.ZERO) != 0 ) if ( val.compareTo(Rational.ZERO) != 0 )
{ {
@ -462,8 +469,9 @@ class RatPoly
* @param val the other polynomial * @param val the other polynomial
* @param nmax the maximum degree of the Taylor expansion of the result. * @param nmax the maximum degree of the Taylor expansion of the result.
* @return the Taylor expansion of this/val up to degree nmax. * @return the Taylor expansion of this/val up to degree nmax.
* @throws Errore
*/ */
public RatPoly divide(final RatPoly val,int nmax) public RatPoly divide(final RatPoly val,int nmax) throws Errore
{ {
RatPoly num = this ; RatPoly num = this ;
RatPoly denom = val ; RatPoly denom = val ;
@ -501,9 +509,10 @@ class RatPoly
* @return A vector with [0] containg the polynomial of degree which is the * @return A vector with [0] containg the polynomial of degree which is the
* difference of thisdegree and the degree of val. [1] the remainder polynomial. * difference of thisdegree and the degree of val. [1] the remainder polynomial.
* This = returnvalue[0] + returnvalue[1]/val . * This = returnvalue[0] + returnvalue[1]/val .
* @throws Errore
* @since 2012-03-01 * @since 2012-03-01
*/ */
public RatPoly[] divideAndRemainder(final RatPoly val) public RatPoly[] divideAndRemainder(final RatPoly val) throws Errore
{ {
RatPoly[] ret = new RatPoly[2] ; RatPoly[] ret = new RatPoly[2] ;
/* remove any high-order zeros /* remove any high-order zeros
@ -648,9 +657,10 @@ class RatPoly
/** Scale coefficients such that the coefficient in front of the maximum degree is unity. /** Scale coefficients such that the coefficient in front of the maximum degree is unity.
* @return The scaled polynomial * @return The scaled polynomial
* @throws Errore
* @since 2008-10-26 * @since 2008-10-26
*/ */
public RatPoly monic() public RatPoly monic() throws Errore
{ {
RatPoly m = new RatPoly() ; RatPoly m = new RatPoly() ;
final int d = degree() ; final int d = degree() ;
@ -776,9 +786,10 @@ class RatPoly
/** Generate the roots of the polynomial in floating point arithmetic. /** Generate the roots of the polynomial in floating point arithmetic.
* @see <a href="http://en.wikipedia.org/wiki/Durand-Kerner_method">Durand Kerner method</a> * @see <a href="http://en.wikipedia.org/wiki/Durand-Kerner_method">Durand Kerner method</a>
* @param the number of floating point digits * @param the number of floating point digits
* @throws Errore
* @since 2008-10-26 * @since 2008-10-26
*/ */
public Vector<BigComplex> roots(int digits) public Vector<BigComplex> roots(int digits) throws Errore
{ {
RatPoly mon = monic() ; RatPoly mon = monic() ;

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,8 @@ package org.nevec.rjm;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.Scanner; import java.util.Scanner;
import org.warpgate.pi.calculator.Errore;
/** /**
* Exact representations of Wigner 3jm and 3nj values of half-integer arguments. * Exact representations of Wigner 3jm and 3nj values of half-integer arguments.
* *
@ -30,8 +32,9 @@ public class Wigner3j {
* *
* @since 2011-02-15 * @since 2011-02-15
* @author Richard J. Mathar * @author Richard J. Mathar
* @throws Errore
*/ */
static public void main(String args[]) { static public void main(String args[]) throws Errore {
if (args[0].compareTo("6j") == 0) { if (args[0].compareTo("6j") == 0) {
try { try {
String m1 = "6"; String m1 = "6";
@ -102,8 +105,9 @@ public class Wigner3j {
* inequalities is violated or some parameters are out of range. * inequalities is violated or some parameters are out of range.
* @since 2011-02-13 * @since 2011-02-13
* @author Richard J. Mathar * @author Richard J. Mathar
* @throws Errore
*/ */
static public BigSurd wigner3jm(int j1, int j2, int j3, int m1, int m2, int m3) { static public BigSurd wigner3jm(int j1, int j2, int j3, int m1, int m2, int m3) throws Errore {
Rational J1 = new Rational(j1, 2); Rational J1 = new Rational(j1, 2);
Rational J2 = new Rational(j2, 2); Rational J2 = new Rational(j2, 2);
Rational J3 = new Rational(j3, 2); Rational J3 = new Rational(j3, 2);
@ -136,8 +140,9 @@ public class Wigner3j {
* @since 2011-02-13 * @since 2011-02-13
* @since 2012-02-15 Upgraded return value to BigSurdVec * @since 2012-02-15 Upgraded return value to BigSurdVec
* @author Richard J. Mathar * @author Richard J. Mathar
* @throws Errore
*/ */
static public BigSurdVec wigner3j(String m1, String t1, String t2, String j) { static public BigSurdVec wigner3j(String m1, String t1, String t2, String j) throws Errore {
/* /*
* The first number in the line "m" is the number of angular momenta. * The first number in the line "m" is the number of angular momenta.
* The rest of the line is ignored. * The rest of the line is ignored.
@ -265,8 +270,9 @@ public class Wigner3j {
* @since 2011-02-13 * @since 2011-02-13
* @since 2012-02-15 Upgraded to return BigSurdVec * @since 2012-02-15 Upgraded to return BigSurdVec
* @author Richard J. Mathar * @author Richard J. Mathar
* @throws Errore
*/ */
static private BigSurdVec wigner3j(final int[] tvec, final Rational[] J, final Rational[] M, final int[] triadidx) { static private BigSurdVec wigner3j(final int[] tvec, final Rational[] J, final Rational[] M, final int[] triadidx) throws Errore {
/* /*
* The result of the computation. The sum over all m-combinations of the * The result of the computation. The sum over all m-combinations of the
* triads. * triads.
@ -473,8 +479,9 @@ public class Wigner3j {
* inequalities is violated or some parameters are out of range. * inequalities is violated or some parameters are out of range.
* @since 2011-02-13 * @since 2011-02-13
* @author Richard J. Mathar * @author Richard J. Mathar
* @throws Errore
*/ */
static protected BigSurd wigner3jm(Rational j1, Rational j2, Rational j3, Rational m1, Rational m2, Rational m3) { static protected BigSurd wigner3jm(Rational j1, Rational j2, Rational j3, Rational m1, Rational m2, Rational m3) throws Errore {
/* /*
* Check that m1+m2+m3 = 0 * Check that m1+m2+m3 = 0
*/ */

View File

@ -16,6 +16,8 @@ import javax.swing.JList;
import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionListener;
import org.warpgate.pi.calculator.Errore;
/** /**
* An interactive interface to the Wigner3j class. The GUI allows to preselect * An interactive interface to the Wigner3j class. The GUI allows to preselect
* one of the symbols if the number of j-terms is small (6j up to 15j), or to * one of the symbols if the number of j-terms is small (6j up to 15j), or to
@ -133,9 +135,10 @@ public class Wigner3jGUI implements ActionListener, ListSelectionListener {
} /* init */ } /* init */
/** /**
* @throws Errore
* @since 2010-08-27 * @since 2010-08-27
*/ */
public void compute() { public void compute() throws Errore {
String tr = inpGtria.getText(); String tr = inpGtria.getText();
String[] trias = new String[4]; String[] trias = new String[4];
@ -206,7 +209,12 @@ public class Wigner3jGUI implements ActionListener, ListSelectionListener {
*/ */
if (lin == "compute") { if (lin == "compute") {
outG.setText(""); outG.setText("");
try {
compute(); compute();
} catch (Errore e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} }
} /* actionPerformed */ } /* actionPerformed */

View File

@ -1,6 +1,6 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import org.nevec.rjm.BigSurdVec; import org.nevec.rjm.NumeroAvanzatoVec;
public class Calculator { public class Calculator {
@ -10,7 +10,7 @@ public class Calculator {
public Termine calcolarisultato(String string) throws Errore { public Termine calcolarisultato(String string) throws Errore {
System.out.println("INPUT: " + string); System.out.println("INPUT: " + string);
Parentesi espressione = new Parentesi(string, ""); Parentesi espressione = new Parentesi(string);
return espressione.calcola(); return espressione.calcola();
} }

View File

@ -1,6 +1,11 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import org.nevec.rjm.BigSurdVec; import java.awt.Color;
import java.awt.Graphics;
import org.nevec.rjm.NumeroAvanzatoVec;
import org.nevec.rjm.Rational;
import org.warp.engine.Display;
public class Divisione extends FunzioneDueValori { public class Divisione extends FunzioneDueValori {
@ -15,9 +20,150 @@ public class Divisione extends FunzioneDueValori {
@Override @Override
public Termine calcola() throws Errore { public Termine calcola() throws Errore {
if (getVariable2().calcola().getTerm().compareTo(BigSurdVec.ZERO) == 0) { if (variable2 == null || variable1 == null) {
return new Termine("0");
}
if (variable2.calcola().getTerm().compareTo(NumeroAvanzatoVec.ZERO) == 0) {
throw new Errore(Errori.DIVISION_BY_ZERO); throw new Errore(Errori.DIVISION_BY_ZERO);
} }
return getVariable1().calcola().divide(getVariable2().calcola()); return variable1.calcola().divide(variable2.calcola());
}
public boolean hasMinus() {
String numerator = variable1.toString();
if (numerator.startsWith("-")) {
return true;
}
return false;
}
public void draw(int x, int y, Display g, boolean small, boolean drawMinus) {
boolean beforedrawminus = this.drawMinus;
this.drawMinus = drawMinus;
draw(x, y, g, small);
this.drawMinus = beforedrawminus;
}
private boolean drawMinus = true;
@Override
public void draw(int x, int y, Display g, boolean small) {
Object var1 = variable1;
Object var2 = variable2;
small = true;
boolean minus = false;
int minusw = 0;
int minush = 0;
String numerator = ((Funzione)var1).toString();
if (numerator.startsWith("-") && ((Funzione)var1) instanceof Termine && ((Termine)var1).term.isBigInteger(true)) {
minus = true;
numerator = numerator.substring(1);
}
int w1 = 0;
int h1 = 0;
if (minus) {
w1 = Utils.getPlainTextWidth(numerator);
h1 = Utils.getFontHeight(small);
} else {
w1 = ((Funzione)var1).getWidth();
h1 = ((Funzione)var1).getHeight(small);
}
int w2 = ((Funzione)var2).getWidth();
int maxw;
if (w1 > w2) {
maxw = 1+w1+1;
} else {
maxw = 1+w2+1;
}
if (minus && drawMinus) {
minusw = Utils.getPlainTextWidth("-")+1;
minush = Utils.getFontHeight(small);
Utils.writeLetter(g, "-", x, y+h1+1+1-(minush/2), small);
Utils.writeLetter(g, numerator, (int)(x+minusw+1+((double)(maxw-w1))/2d), y, small);
} else {
((Funzione)var1).draw((int)(x+minusw+1+((double)(maxw-w1))/2d), y, g, true);
}
((Funzione)var2).draw((int)(x+minusw+1+((double)(maxw-w2))/2d), y+h1+1+1+1, g, true);
g.setColor(Color.BLACK);
g.fillRect(x+minusw+1, y+h1+1, maxw, 1);
}
public int getHeight(boolean small, boolean drawMinus) {
boolean beforedrawminus = this.drawMinus;
this.drawMinus = drawMinus;
int h = getHeight(small);
this.drawMinus = beforedrawminus;
return h;
}
@Override
public int getHeight(boolean small) {
boolean minus = false;
small = true;
String numerator = variable1.toString();
if (numerator.startsWith("-") && variable1 instanceof Termine && ((Termine) variable1).term.isBigInteger(true)) {
minus = true;
numerator = numerator.substring(1);
}
int w1 = 0;
int h1 = 0;
if (minus) {
w1 = Utils.getPlainTextWidth(numerator);
h1 = Utils.getFontHeight(small);
} else {
w1 = variable1.getWidth();
h1 = variable1.getHeight(small);
}
int w2 = variable2.getWidth();
int h2 = variable2.getHeight(small);
int maxw;
if (w1 > w2) {
maxw = 1+w1+1;
} else {
maxw = 1+w2+1;
}
return h1+3+h2;
}
@Override
public int getLine(boolean small) {
return variable1.getHeight(true)+1;
}
public int getWidth(boolean drawMinus) {
boolean beforedrawminus = this.drawMinus;
this.drawMinus = drawMinus;
int w = getWidth();
this.drawMinus = beforedrawminus;
return w;
}
@Override
public int getWidth() {
boolean minus = false;
String numerator = variable1.toString();
if (numerator.startsWith("-") && variable1 instanceof Termine && ((Termine) variable1).term.isBigInteger(true)) {
minus = true;
numerator = numerator.substring(1);
}
int w1 = 0;
int h1 = 0;
if (minus) {
w1 = Utils.getPlainTextWidth(numerator);
} else {
w1 = variable1.getWidth();
}
int w2 = variable2.getWidth();
int maxw;
if (w1 > w2) {
maxw = 1+w1+1;
} else {
maxw = 1+w2+1;
}
if (minus && drawMinus) {
return Utils.getPlainTextWidth("-")+1+maxw+1;
} else {
return maxw+2;
}
} }
} }

View File

@ -4,5 +4,10 @@ public enum Errori {
ERROR, ERROR,
DIVISION_BY_ZERO, DIVISION_BY_ZERO,
UNBALANCED_BRACKETS, UNBALANCED_BRACKETS,
NOT_IMPLEMENTED NOT_IMPLEMENTED,
NEGATIVE_PARAMETER,
NUMBER_TOO_LARGE,
NUMBER_TOO_SMALL,
CONVERSION_ERROR,
SYNTAX_ERROR
} }

View File

@ -1,6 +1,14 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import org.warp.engine.Display;
import com.rits.cloning.Cloner;
public interface Funzione { public interface Funzione {
public String simbolo(); public String simbolo();
public Termine calcola() throws Errore; public Termine calcola() throws Errore;
public void draw(int x, int y, Display g, boolean small);
public int getWidth();
public int getHeight(boolean small);
public int getLine(boolean small);
} }

View File

@ -0,0 +1,66 @@
package org.warpgate.pi.calculator;
import org.nevec.rjm.NumeroAvanzatoVec;
import org.warp.engine.Display;
import com.rits.cloning.Cloner;
public abstract class FunzioneAnteriore implements Funzione {
public FunzioneAnteriore(Funzione value) {
setVariable(value);
}
protected Funzione variable = new Termine(NumeroAvanzatoVec.ZERO);
public Funzione getVariable() {
return variable;
}
public void setVariable(Funzione value) {
variable = value;
}
@Override
public abstract String simbolo();
@Override
public abstract Termine calcola() throws Errore;
@Override
public void draw(int x, int y, Display g, boolean small) {
int w1 = getVariable().getWidth();
float h1 = getVariable().getHeight(small);
int wsegno = Utils.getPlainTextWidth(simbolo());
float hsegno = Utils.getFontHeight(small);
float maxh = getHeight(small);
Utils.writeLetter(g, simbolo(), x, (int)Math.floor(y+(maxh-hsegno)/2), small);
getVariable().draw(x+wsegno+1, (int)Math.floor(y+(maxh-h1)/2), g, small);
}
@Override
public int getWidth() {
return Utils.getPlainTextWidth(simbolo())+1+getVariable().getWidth();
}
@Override
public int getHeight(boolean small) {
return variable.getHeight(small);
}
@Override
public int getLine(boolean small) {
return variable.getLine(small);
}
@Override
public String toString() {
try {
return calcola().toString();
} catch (Errore e) {
return e.id.toString();
}
}
@Override
public FunzioneAnteriore clone() {
Cloner cloner = new Cloner();
return cloner.deepClone(this);
}
}

View File

@ -1,6 +1,9 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import org.nevec.rjm.Rational; import org.nevec.rjm.Rational;
import org.warp.engine.Display;
import com.rits.cloning.Cloner;
public abstract class FunzioneDueValori implements Funzione { public abstract class FunzioneDueValori implements Funzione {
public FunzioneDueValori(Funzione value1, Funzione value2) { public FunzioneDueValori(Funzione value1, Funzione value2) {
@ -25,4 +28,65 @@ public abstract class FunzioneDueValori implements Funzione {
public abstract String simbolo(); public abstract String simbolo();
@Override @Override
public abstract Termine calcola() throws Errore; public abstract Termine calcola() throws Errore;
@Override
public void draw(int x, int y, Display g, boolean small) {
int ln = getLine(small);
int dx = 0;
variable1.draw(dx+x, ln-variable1.getLine(small)+y, g, small);
dx+=variable1.getWidth()+1;
if (drawSignum()) {
Utils.writeLetter(g, simbolo(), dx+x, ln-Utils.getFontHeight(small)/2+y, small);
dx+=1;
dx+=Utils.getPlainTextWidth(simbolo());
}
variable2.draw(dx+x, ln-variable2.getLine(small)+y, g, small);
}
@Override
public int getWidth() {
return variable1.getWidth()+1+ (drawSignum() ? Utils.getPlainTextWidth(simbolo())+1 : 0) +variable2.getWidth();
}
@Override
public int getHeight(boolean small) {
Funzione tmin = variable1;
Funzione tmax = variable1;
if (tmin == null || variable2.getLine(small) >= tmin.getLine(small)) {
tmin = variable2;
}
if (tmax == null || variable2.getHeight(small) - variable2.getLine(small) >= tmax.getHeight(small) - tmax.getLine(small)) {
tmax = variable2;
}
return tmin.getLine(small) + tmax.getHeight(small) - tmax.getLine(small);
}
@Override
public int getLine(boolean small) {
Funzione tl = variable1;
if (tl == null || variable2.getLine(small) >= tl.getLine(small)) {
tl = variable2;
}
return tl.getLine(small);
}
@Override
public String toString() {
try {
return calcola().toString();
} catch (Errore e) {
return e.id.toString();
}
}
@Override
public FunzioneDueValori clone() {
Cloner cloner = new Cloner();
return cloner.deepClone(this);
}
public boolean drawSignum() {
return true;
}
} }

View File

@ -3,6 +3,8 @@ package org.warpgate.pi.calculator;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import com.rits.cloning.Cloner;
public abstract class FunzioneMultipla implements Funzione { public abstract class FunzioneMultipla implements Funzione {
public FunzioneMultipla() { public FunzioneMultipla() {
setVariables(new Funzione[]{}); setVariables(new Funzione[]{});
@ -51,4 +53,19 @@ public abstract class FunzioneMultipla implements Funzione {
public abstract String simbolo(); public abstract String simbolo();
@Override @Override
public abstract Termine calcola() throws Errore; public abstract Termine calcola() throws Errore;
@Override
public String toString() {
try {
return calcola().toString();
} catch (Errore e) {
return e.id.toString();
}
}
@Override
public Funzione clone() {
Cloner cloner = new Cloner();
return cloner.deepClone(this);
}
} }

View File

@ -1,20 +0,0 @@
package org.warpgate.pi.calculator;
import org.nevec.rjm.BigSurdVec;
public abstract class FunzioneSingola implements Funzione {
public FunzioneSingola(Funzione value) {
setVariable(value);
}
protected Funzione variable = new Termine(BigSurdVec.ZERO);
public Funzione getVariable() {
return variable;
}
public void setVariable(Funzione value) {
variable = value;
}
@Override
public abstract String simbolo();
@Override
public abstract Termine calcola() throws Errore;
}

View File

@ -1,9 +1,86 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
public class Main { import java.awt.Color;
public static void main(String[] args) { import java.awt.Font;
Calculator c = new Calculator(false); import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.gatecraft.game2d.utils.BitmapImage;
import org.nevec.rjm.NumeroAvanzato;
import org.nevec.rjm.NumeroAvanzatoVec;
import org.nevec.rjm.Rational;
import org.warp.engine.ActionInterface;
import org.warp.engine.Display;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.util.Duration;
public class Main implements ActionInterface {
public static final int[] screenSize = new int[]{300, 150};
public static final int screenScale = 1;
public volatile static Display d;
@SuppressWarnings({ "unchecked", "rawtypes" })
public Main() {
Display.start(this, screenSize[0], screenSize[1]);
d = Display.INSTANCE;
d.g().setFill(new javafx.scene.paint.Color(0.796875, 0.90234375, 0.828125, 1));
d.g().fillRect(0, 0, screenSize[0], screenSize[0]);
Utils.writeLetter(d, "Loading...".toUpperCase(), (screenSize[0]-Utils.getPlainTextWidth("Loading...".toUpperCase()))/2, (screenSize[1]-Utils.getFontHeight(false))/2, false);
try { try {
//Parentesi f = new Parentesi("(Ⓐ(2X)*3Y)/(5Z^2)+(Ⓐ(11A)*13B)/(7CZ)=19XZ");
//PARENTESI CON CALCOLI
//Funzione f = new Sottrazione(new Somma(new Parentesi("Ⓐ9/2+Ⓐ7/2", "").calcola(), new Termine("3.5")), new Parentesi("3*2√14","").calcola());
//PARENTESI CON DUE NUMERI FRAZIONALI COMPLETI CON INCOGNITE:
//Funzione f = new Parentesi("(Ⓐ(2X)*3Y)/(5Z^2)+(Ⓐ(11A)*13B)/(7CZ)", "");
//PARENTESI CON DUE NUMERI FRAZIONALI DISALLINEATI GRAFICAMENTE:
//Funzione f = new Parentesi("((5^2-1)/2)/5-5/(5/2)=2", "");
//TERMINE DI PROVA COMPLETO:
//Funzione f = new Termine(new NumeroAvanzato(new Rational(3, 2), new Rational(7, 1), new Incognite(new Incognita('X', Rational.ONE)), new Incognite(new Incognita('Y', Rational.ONE)), new Incognite(new Incognita('z', Rational.ONE))));
//PARENTESI REALISTICA CON INCOGNITE:
//Funzione f = new Equazione(new Parentesi("X^2+(MX-M+4)^2-4X-4(MX-M+4)^2+7", ""), new Termine("0"));
//POTENZA:
//Funzione f = new Parentesi("(MX-M+4)^2", "");
//NUMERO SEMPLICE LUNGO:
//Funzione f = new Parentesi("-1219999799999996934.42229", "");
//:
//Funzione f = new Parentesi("5Y+XY=2", "")
equazione = "";
c = new Calculator(true);
f = new Parentesi(equazione);
f2 = f.calcolaSistema();
ew1 = f.getWidth();
ew2 = f2.getWidth();
eh2 = f2.getHeight(false);
x1 = 2;
x2 = 2;
requiresleep1 = false;
requiresleep2 = false;
aftersleep = false;
autoscroll = false;
final Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(true);
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(1000/25), new EventHandler() {
@Override
public void handle(Event arg0) {
refresh();
}
}));
timeline.play();
/*
long start = System.nanoTime(); long start = System.nanoTime();
Termine result = c.calcolarisultato("((5^2+3√(100/0.1))*Ⓐ7+9/15*2√(26/2))/21"); Termine result = c.calcolarisultato("((5^2+3√(100/0.1))*Ⓐ7+9/15*2√(26/2))/21");
long end = System.nanoTime(); long end = System.nanoTime();
@ -20,8 +97,120 @@ public class Main {
System.out.println("Is an equation: " + eresult.isAnEquation); System.out.println("Is an equation: " + eresult.isAnEquation);
System.out.println("L-R: " + eresult.LR); System.out.println("L-R: " + eresult.LR);
System.out.println("Time elapsed: " + (((double) timeElapsed / 1000000000)) + "\n"); System.out.println("Time elapsed: " + (((double) timeElapsed / 1000000000)) + "\n");
*/
} catch (Errore e) { } catch (Errore e) {
d.setColor(new Color(204, 231, 212));
d.fillRect(0, 0, screenSize[0], screenSize[1]);
Utils.writeLetter(d, e.id.toString(), 2, 2, false);
System.err.println(e.id); System.err.println(e.id);
} }
} }
public static volatile String equazione = "";
public static Calculator c;
public static Parentesi f;
public static Funzione f2;
public static int ew1;
public static int ew2;
public static int eh2;
public static int x1;
public static int x2;
public static boolean requiresleep1;
public static boolean requiresleep2;
public static boolean aftersleep;
public static boolean autoscroll;
protected static void refresh() {
long delta = System.currentTimeMillis();
d.setColor(new Color(204, 231, 212));
d.fillRect(0, 0, screenSize[0], screenSize[1]);
if (equazione == "") {
d.setColor(Color.BLACK);
d.drawString("Scrivi qua sopra un'espressione,".toUpperCase(), 10, 20);
d.drawString("dopodiche premi il tasto execute".toUpperCase(), 10, 35);
d.setColor(Color.RED);
d.drawBoldString( "Leggi ATTENZIONE.txt!".toUpperCase(), 10, 60);
} else {
if (ew1 + x1 + 5 > screenSize[0] && !requiresleep1 && autoscroll) {
x1-=1;
} else if(autoscroll) {
requiresleep1 = true;
}
if (ew2 + x2 + 5 > screenSize[0] && !requiresleep2 && autoscroll) {
x2-=1;
} else if(autoscroll) {
requiresleep2 = true;
}
if (requiresleep1 && requiresleep2 && autoscroll) {
requiresleep1 = false;
requiresleep2 = false;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
x1 = 2;
x2 = 2;
aftersleep = true;
}
f.draw(x1,2,d, false);
f2.draw(x2,screenSize[1]-2-eh2,d, false);
}
if (aftersleep && autoscroll) {
aftersleep = false;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
delta = System.currentTimeMillis() - delta;
if (50-delta > 0 && autoscroll) {
Thread.sleep(50-delta);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
new Main();
}
@Override
public synchronized void refresh(String args) {
equazione = args.replace("sqrt", "").replace("^", "");
c = new Calculator(true);
try {
f = new Parentesi(equazione);
} catch (Errore e) {
e.printStackTrace();
}
try {
f2 = f.calcolaSistema();
} catch (Errore e) {
e.printStackTrace();
}
ew1 = f.getWidth();
ew2 = f2.getWidth();
eh2 = f2.getHeight(false);
x1 = 2;
x2 = 2;
requiresleep1 = false;
requiresleep2 = false;
aftersleep = false;
autoscroll = false;
}
} }

View File

@ -1,5 +1,10 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import java.awt.Graphics;
import java.math.BigInteger;
import org.nevec.rjm.NumeroAvanzatoVec;
public class Moltiplicazione extends FunzioneDueValori { public class Moltiplicazione extends FunzioneDueValori {
public Moltiplicazione(Funzione value1, Funzione value2) { public Moltiplicazione(Funzione value1, Funzione value2) {
@ -15,4 +20,65 @@ public class Moltiplicazione extends FunzioneDueValori {
public Termine calcola() throws Errore { public Termine calcola() throws Errore {
return getVariable1().calcola().multiply(getVariable2().calcola()); return getVariable1().calcola().multiply(getVariable2().calcola());
} }
@Override
public boolean drawSignum() {
Funzione[] tmpVar = new Funzione[]{variable1, variable2};
boolean[] ok = new boolean[]{false, false};
for (int val = 0; val < 2; val++) {
while (!ok[val]) {
if (tmpVar[val] instanceof Divisione) {
ok[0] = true;
ok[1] = true;
} else if (tmpVar[val] instanceof Incognita) {
ok[val] = true;
} else if (tmpVar[val] instanceof Termine) {
if (val == 0) {
ok[val] = true;
} else {
if (!(tmpVar[0] instanceof Termine)) {
ok[val] = true;
} else {
if (((Termine)tmpVar[0]).term.isBigInteger(false)) {
if (((Termine)tmpVar[val]).term.toBigInteger(true).compareTo(new BigInteger("1")) == 0) {
if (((Termine)tmpVar[val]).term.toNumeroAvanzato().getIncognitey().count() > 0) {
ok[val] = true;
} else {
break;
}
} else {
break;
}
} else {
ok[val] = true;
}
}
}
} else if (tmpVar[val] instanceof Potenza) {
tmpVar[val] = ((Potenza)tmpVar[val]).variable1;
} else if (tmpVar[val] instanceof Radice) {
ok[val] = true;
} else if (tmpVar[val] instanceof RadiceQuadrata) {
ok[val] = true;
} else if (tmpVar[val] instanceof Parentesi) {
ok[0] = true;
ok[1] = true;
} else if (tmpVar[val] instanceof FunzioneDueValori) {
if (val == 0) {
tmpVar[val] = ((FunzioneDueValori)tmpVar[val]).variable2;
} else {
tmpVar[val] = ((FunzioneDueValori)tmpVar[val]).variable1;
}
} else if (tmpVar[val] instanceof FunzioneAnteriore) {
tmpVar[val] = ((FunzioneAnteriore)tmpVar[val]).variable;
}
}
}
if (ok[0] == true && ok[1] == true) {
return false;
} else {
return true;
}
}
} }

View File

@ -3,11 +3,14 @@ package org.warpgate.pi.calculator;
import static org.warpgate.pi.calculator.Utils.ArrayToRegex; import static org.warpgate.pi.calculator.Utils.ArrayToRegex;
import static org.warpgate.pi.calculator.Utils.concat; import static org.warpgate.pi.calculator.Utils.concat;
import java.awt.Color;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.nevec.rjm.BigSurdVec; import org.nevec.rjm.NumeroAvanzato;
import org.nevec.rjm.NumeroAvanzatoVec;
import org.warp.engine.Display;
public class Parentesi extends FunzioneMultipla { public class Parentesi extends FunzioneMultipla {
@ -19,12 +22,19 @@ public class Parentesi extends FunzioneMultipla {
super(values); super(values);
} }
public Parentesi(String string, String debugSpaces) throws Errore { private boolean parentesiIniziale = false;
public Parentesi(String string) throws Errore {
this(string, "", true);
}
public Parentesi(String string, String debugSpaces, boolean parentesiIniziale) throws Errore {
super(); super();
this.parentesiIniziale = parentesiIniziale;
try{ try{
//Se l'espressione è già un numero: //Se l'espressione è già un numero:
setVariables(new Funzione[]{new Termine(string)}); setVariables(new Funzione[]{new Termine(string)});
Utils.debug.println(debugSpaces+"•Result:"+string); Utils.debug.println(debugSpaces+"(Value:"+string+")");
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
String processExpression = string; String processExpression = string;
@ -33,6 +43,25 @@ public class Parentesi extends FunzioneMultipla {
//Se l'espressione non è già un numero: //Se l'espressione non è già un numero:
//Controlla se ci sono più di un uguale
int equationsFound = 0;
int systemsFound = 0;
for (char c : processExpression.toCharArray()) {
if ((""+c).equals(Simboli.EQUATION)) {
equationsFound+=1;
}
if ((""+c).equals(Simboli.SYSTEM)) {
equationsFound+=1;
}
}
if (equationsFound == 1 && systemsFound == 0) {
processExpression = Simboli.SYSTEM+processExpression;
systemsFound+=1;
}
if (equationsFound != systemsFound) {
throw new Errore(Errori.SYNTAX_ERROR);
}
//Correggi i segni ++ e -- in eccesso //Correggi i segni ++ e -- in eccesso
Pattern pattern = Pattern.compile("\\+\\++?|\\-\\-+?"); Pattern pattern = Pattern.compile("\\+\\++?|\\-\\-+?");
Matcher matcher = pattern.matcher(processExpression); Matcher matcher = pattern.matcher(processExpression);
@ -50,7 +79,7 @@ public class Parentesi extends FunzioneMultipla {
while (matcher.find()) { while (matcher.find()) {
cambiati = true; cambiati = true;
String correzione = "-"; String correzione = "-";
processExpression = processExpression.substring(0, matcher.start(0)+1)+correzione+processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length()); processExpression = processExpression.substring(0, matcher.start(0))+correzione+processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length());
matcher = pattern.matcher(processExpression); matcher = pattern.matcher(processExpression);
} }
@ -59,6 +88,12 @@ public class Parentesi extends FunzioneMultipla {
cambiati = true; cambiati = true;
processExpression = processExpression.replace("(+", "("); processExpression = processExpression.replace("(+", "(");
} }
//Cambia i segni appena prima le parentesi
if (processExpression.contains("-(")) {
cambiati = true;
processExpression = processExpression.replace("-(", "-1*(");
}
//Rimuovi i segni appena dopo l'inizio //Rimuovi i segni appena dopo l'inizio
if (processExpression.startsWith("+")) { if (processExpression.startsWith("+")) {
cambiati = true; cambiati = true;
@ -87,7 +122,7 @@ public class Parentesi extends FunzioneMultipla {
} }
//Correggi i segni - in +- //Correggi i segni - in +-
pattern = Pattern.compile("[^"+Utils.ArrayToRegex(concat(concat(Simboli.funzioni(),Simboli.parentesi()), Simboli.segni(true)))+"]-"); pattern = Pattern.compile("[^"+Utils.ArrayToRegex(concat(concat(Simboli.funzioni(),new String[]{Simboli.PARENTHESIS_OPEN}), Simboli.segni(true)))+"]-");
matcher = pattern.matcher(processExpression); matcher = pattern.matcher(processExpression);
while (matcher.find()) { while (matcher.find()) {
cambiati = true; cambiati = true;
@ -110,13 +145,13 @@ public class Parentesi extends FunzioneMultipla {
String beforeexp = processExpression.substring(0, matcher.start(0)); String beforeexp = processExpression.substring(0, matcher.start(0));
String newexp = matcher.group(0).substring(1, matcher.group(0).length()-1); String newexp = matcher.group(0).substring(1, matcher.group(0).length()-1);
String afterexp = processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length()); String afterexp = processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length());
if (Pattern.compile("[^"+Utils.ArrayToRegex(Utils.add(concat(Simboli.funzioni(), Simboli.segni(true)), "("))+"]$").matcher(beforeexp).find()) { if (Pattern.compile("[^\\-"+Utils.ArrayToRegex(Utils.add(concat(Simboli.funzioni(), concat(Simboli.segni(true), Simboli.sintassiGenerale())), "("))+"]$").matcher(beforeexp).find()) {
//Se la stringa precedente finisce con un numero //Se la stringa precedente finisce con un numero
beforeexp += "*"; beforeexp += Simboli.MULTIPLICATION;
} }
if (Pattern.compile("^[^"+Utils.ArrayToRegex(Utils.add(concat(Simboli.funzioni(), Simboli.segni(true)), ")"))+"]").matcher(afterexp).find()) { if (Pattern.compile("^[^\\-"+Utils.ArrayToRegex(Utils.add(concat(Simboli.funzioni(), concat(Simboli.segni(true), Simboli.sintassiGenerale())), ")"))+"]").matcher(afterexp).find()) {
//Se la stringa successiva inizia con un numero //Se la stringa successiva inizia con un numero
afterexp = "*"+afterexp; afterexp = Simboli.MULTIPLICATION+afterexp;
} }
processExpression = beforeexp+""+newexp+""+afterexp; processExpression = beforeexp+""+newexp+""+afterexp;
matcher = pattern.matcher(processExpression); matcher = pattern.matcher(processExpression);
@ -137,7 +172,8 @@ public class Parentesi extends FunzioneMultipla {
Parentesi parentesiNonSuddivisaCorrettamente = new Parentesi(); Parentesi parentesiNonSuddivisaCorrettamente = new Parentesi();
parentesiNonSuddivisaCorrettamente.setVariables(new Funzione[]{}); parentesiNonSuddivisaCorrettamente.setVariables(new Funzione[]{});
String tmp = ""; String tmp = "";
final String[] funzioni = concat(concat(Simboli.funzioni(), Simboli.parentesi()), Simboli.segni(true)); Incognite tmpI = new Incognite();
final String[] funzioni = concat(concat(concat(concat(Simboli.funzioni(), Simboli.parentesi()), Simboli.segni(true)), Simboli.incognite()), Simboli.sintassiGenerale());
for (int i = 0; i < processExpression.length(); i++) { for (int i = 0; i < processExpression.length(); i++) {
//Per ogni carattere cerca se è un numero o una funzione: //Per ogni carattere cerca se è un numero o una funzione:
String charI = processExpression.charAt(i)+""; String charI = processExpression.charAt(i)+"";
@ -164,6 +200,12 @@ public class Parentesi extends FunzioneMultipla {
case Simboli.POTENZA: case Simboli.POTENZA:
f = new Potenza(null, null); f = new Potenza(null, null);
break; break;
case Simboli.EQUATION:
f = new Equazione(null, null);
break;
case Simboli.SYSTEM:
f = new ParteSistema(null);
break;
case Simboli.PARENTHESIS_OPEN: case Simboli.PARENTHESIS_OPEN:
//cerca l'ultima parentesi chiusa //cerca l'ultima parentesi chiusa
int startIndex = i; int startIndex = i;
@ -194,13 +236,47 @@ public class Parentesi extends FunzioneMultipla {
tmpExpr += processExpression.charAt(i); tmpExpr += processExpression.charAt(i);
i++; i++;
} }
f = new Parentesi(tmpExpr, debugSpaces); f = new Parentesi(tmpExpr, debugSpaces, false);
break; break;
default: default:
if (Utils.isInArray(charI, Simboli.incognite())) {
//Fallback
NumeroAvanzato na = NumeroAvanzato.ONE;
Incognite iy = na.getIncognitey();
iy.incognite.add(new Incognita(charI.charAt(0), 1, 1));
na = na.setIncognitey(iy);
f = new Termine(na);
} else {
throw new java.lang.RuntimeException("Il carattere "+charI+" non è tra le funzioni designate!\nAggiungerlo ad esse o rimuovere il carattere dall'espressione!"); throw new java.lang.RuntimeException("Il carattere "+charI+" non è tra le funzioni designate!\nAggiungerlo ad esse o rimuovere il carattere dall'espressione!");
} }
}
if (f instanceof Parentesi) { if (f instanceof Parentesi) {
tmp = ""; tmp = "";
} else if (f instanceof Termine) {
if (parentesiNonSuddivisaCorrettamente.getVariablesLength() == 0) {
if (tmp.length() > 0) {
parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Termine(tmp));
Utils.debug.println(debugSpaces+"•Added value to expression:"+tmp);
parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Moltiplicazione(null, null));
Utils.debug.println(debugSpaces+"•Added variable to expression:"+new Moltiplicazione(null, null).simbolo());
}
} else {
if (tmp.length() > 0) {
if (parentesiNonSuddivisaCorrettamente.getVariable(parentesiNonSuddivisaCorrettamente.getVariablesLength()-1) instanceof Termine) {
parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Moltiplicazione(null, null));
Utils.debug.println(debugSpaces+"•Added variable to expression:"+new Moltiplicazione(null, null).simbolo());
}
if (tmp.equals("-")) {
tmp = "-1";
}
parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Termine(tmp));
Utils.debug.println(debugSpaces+"•Added value to expression:"+tmp);
}
if (tmp.length() > 0 || parentesiNonSuddivisaCorrettamente.getVariable(parentesiNonSuddivisaCorrettamente.getVariablesLength()-1) instanceof Termine) {
parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Moltiplicazione(null, null));
Utils.debug.println(debugSpaces+"•Added variable to expression:"+new Moltiplicazione(null, null).simbolo());
}
}
} else { } else {
if (tmp.length() != 0) { if (tmp.length() != 0) {
parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Termine(tmp)); parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Termine(tmp));
@ -212,7 +288,7 @@ public class Parentesi extends FunzioneMultipla {
tmp = ""; tmp = "";
} else { } else {
try{ try{
if (!(charI.equals("-") || charI.equals("."))) { if (charI.equals("-") == false && charI.equals(".") == false) {
Double.parseDouble(tmp + charI); Double.parseDouble(tmp + charI);
} }
//Se il carattere è un numero intero, un segno negativo, o un punto //Se il carattere è un numero intero, un segno negativo, o un punto
@ -230,9 +306,22 @@ public class Parentesi extends FunzioneMultipla {
int dsl = debugSpaces.length();debugSpaces = "";for (int i = 0; i < dsl-2; i++) {debugSpaces += " ";} int dsl = debugSpaces.length();debugSpaces = "";for (int i = 0; i < dsl-2; i++) {debugSpaces += " ";}
Utils.debug.println(debugSpaces+"•Finished the subdivision in classes."); Utils.debug.println(debugSpaces+"•Finished the subdivision in classes.");
//Fine suddivisione di insieme //Fine suddivisione di insieme
Utils.debug.println(debugSpaces+"•Removing useless parentheses");
for (int i = 0; i < parentesiNonSuddivisaCorrettamente.variables.length; i++) {
if (parentesiNonSuddivisaCorrettamente.variables[i] instanceof Parentesi) {
Parentesi par = (Parentesi) parentesiNonSuddivisaCorrettamente.variables[i];
if (par.variables.length == 1) {
Funzione subFunz = par.variables[0];
if (subFunz instanceof Parentesi || subFunz instanceof Termine) {
parentesiNonSuddivisaCorrettamente.variables[i] = subFunz;
Utils.debug.println(debugSpaces+" •Useless parentheses removed");
}
}
}
}
//Inizia l'affinazione dell'espressione //Inizia l'affinazione dell'espressione
Utils.debug.println(debugSpaces+"•Pushing classes..."); Utils.debug.println(debugSpaces+"•Pushing classes...");
@ -246,8 +335,6 @@ public class Parentesi extends FunzioneMultipla {
Utils.debug.println(debugSpaces+" •Correcting classes:"); Utils.debug.println(debugSpaces+" •Correcting classes:");
debugSpaces += " ";
int before = 0; int before = 0;
String fase = "funzioniSN"; String fase = "funzioniSN";
int n = 0; int n = 0;
@ -255,57 +342,157 @@ public class Parentesi extends FunzioneMultipla {
before = funzioniOLD.size(); before = funzioniOLD.size();
int i = 0; int i = 0;
boolean change = false; boolean change = false;
if (Utils.ciSonoSoloNumeriESomme(funzioniOLD)) { if (Utils.ciSonoFunzioniSNnonImpostate(funzioniOLD)) {
fase = "somme"; //QUARTA FASE
} else if (Utils.ciSonoFunzioniSNnonImpostate(funzioniOLD)) {
fase = "funzioniSN"; // PRIMA FASE fase = "funzioniSN"; // PRIMA FASE
} else if (Utils.ciSonoAltreFunzioni(funzioniOLD)) { } else if (Utils.ciSonoFunzioniNSNnonImpostate(funzioniOLD)) {
fase = "funzioniNSN"; //SECONDA FASE fase = "funzioniNSN"; //SECONDA FASE
} else { } else if (Utils.ciSonoMoltiplicazioniNonImpostate(funzioniOLD)) {
fase = "moltiplicazioni"; //TERZA FASE fase = "moltiplicazioni"; //TERZA FASE
} else if (Utils.ciSonoSommeNonImpostate(funzioniOLD)) {
fase = "somme"; //QUARTA FASE
} else if (Utils.ciSonoEquazioniNonImpostate(funzioniOLD)) {
fase = "equazioni"; //QUINTA FASE
} else if (Utils.ciSonoSistemiNonImpostati(funzioniOLD)) {
fase = "sistemi"; //SESTA FASE
} else {
System.out.println("errore?");//BOH
} }
while (i < funzioniOLD.size() && change == false) { while (i < funzioniOLD.size() && change == false && funzioniOLD.size() > 1) {
Funzione funzioneTMP = funzioniOLD.get(i); Funzione funzioneTMP = funzioniOLD.get(i);
if (funzioneTMP instanceof FunzioneDueValori) { if (funzioneTMP instanceof FunzioneDueValori) {
if (fase != "funzioniSN") { if (fase != "funzioniSN") {
if ( if (
(
fase == "somme" && (funzioneTMP instanceof Somma) == true fase == "somme" && (funzioneTMP instanceof Somma) == true
&&
(
(
funzioneTMP instanceof FunzioneAnteriore
&&
((FunzioneAnteriore)funzioneTMP).variable == null
)
|| ||
(
funzioneTMP instanceof FunzioneDueValori
&&
((FunzioneDueValori)funzioneTMP).variable1 == null
&&
((FunzioneDueValori)funzioneTMP).variable2 == null
)
||
(
!(funzioneTMP instanceof FunzioneAnteriore)
&&
!(funzioneTMP instanceof FunzioneDueValori)
)
)
)
||
(
(fase == "moltiplicazioni" && (funzioneTMP instanceof Somma) == false) (fase == "moltiplicazioni" && (funzioneTMP instanceof Somma) == false)
&&
(
(
funzioneTMP instanceof FunzioneAnteriore
&&
((FunzioneAnteriore)funzioneTMP).variable == null
)
|| ||
(fase == "funzioniNSN" && (funzioneTMP instanceof Somma) == false && (funzioneTMP instanceof Moltiplicazione) == false && (funzioneTMP instanceof Divisione) == false) (
funzioneTMP instanceof FunzioneDueValori
&&
((FunzioneDueValori)funzioneTMP).variable1 == null
&&
((FunzioneDueValori)funzioneTMP).variable2 == null
)
||
(
!(funzioneTMP instanceof FunzioneAnteriore)
&&
!(funzioneTMP instanceof FunzioneDueValori)
)
)
)
||
(fase == "equazioni" && funzioneTMP instanceof Equazione)
||
(
fase == "funzioniNSN"
&&
(funzioneTMP instanceof Somma) == false
&&
(funzioneTMP instanceof Moltiplicazione) == false
&&
(funzioneTMP instanceof Divisione) == false
&&
(
(
funzioneTMP instanceof FunzioneAnteriore
&&
((FunzioneAnteriore)funzioneTMP).variable == null
)
||
(
funzioneTMP instanceof FunzioneDueValori
&&
((FunzioneDueValori)funzioneTMP).variable1 == null
&&
((FunzioneDueValori)funzioneTMP).variable2 == null
)
||
(
!(funzioneTMP instanceof FunzioneAnteriore)
&&
!(funzioneTMP instanceof FunzioneDueValori)
)
)
)
) { ) {
change = true; change = true;
if (i+1 < funzioniOLD.size() && i-1 >= 0 ) { if (i+1 < funzioniOLD.size() && i-1 >= 0 ) {
((FunzioneDueValori) funzioneTMP).setVariable1(funzioniOLD.get(i-1)); ((FunzioneDueValori) funzioneTMP).setVariable1(funzioniOLD.get(i-1));
((FunzioneDueValori) funzioneTMP).setVariable2(funzioniOLD.get(i+1)); ((FunzioneDueValori) funzioneTMP).setVariable2(funzioniOLD.get(i+1));
funzioniOLD.set(i, funzioneTMP.calcola()); funzioniOLD.set(i, funzioneTMP);
//è importante togliere prima gli elementi in fondo e poi quelli davanti, perché gli indici scalano da destra a sinistra. //è importante togliere prima gli elementi in fondo e poi quelli davanti, perché gli indici scalano da destra a sinistra.
funzioniOLD.remove(i+1); funzioniOLD.remove(i+1);
funzioniOLD.remove(i-1); funzioniOLD.remove(i-1);
Utils.debug.println(debugSpaces+" •Set variable to expression:"+funzioneTMP.simbolo()); Utils.debug.println(debugSpaces+" •Set variable to expression:"+funzioneTMP.simbolo());
Utils.debug.println(debugSpaces+" "+"var1="+((FunzioneDueValori) funzioneTMP).getVariable1().calcola()); try {Utils.debug.println(debugSpaces+" "+"var1="+((FunzioneDueValori) funzioneTMP).getVariable1().calcola());} catch (NullPointerException ex2) {}
Utils.debug.println(debugSpaces+" "+"var2="+((FunzioneDueValori) funzioneTMP).getVariable2().calcola()); try {Utils.debug.println(debugSpaces+" "+"var2="+((FunzioneDueValori) funzioneTMP).getVariable2().calcola());} catch (NullPointerException ex2) {}
Utils.debug.println(debugSpaces+" "+"(result)="+((FunzioneDueValori) funzioneTMP).calcola()); try {Utils.debug.println(debugSpaces+" "+"(result)="+((FunzioneDueValori) funzioneTMP).calcola());} catch (NullPointerException ex2) {}
} else { } else {
throw new java.lang.RuntimeException("Argomenti mancanti! Sistemare l'equazione!"); throw new java.lang.RuntimeException("Argomenti mancanti! Sistemare l'equazione!");
} }
} }
} }
} else if (funzioneTMP instanceof FunzioneSingola) { } else if (funzioneTMP instanceof FunzioneAnteriore) {
if (fase == "funzioniSN") { if (
(
fase == "funzioniSN"
&&
((FunzioneAnteriore) funzioneTMP).variable == null
)
||
(
fase == "sistemi"
&&
funzioneTMP instanceof ParteSistema
)
) {
change = true; change = true;
if (i+1 < funzioniOLD.size()) { if (i+1 < funzioniOLD.size()) {
((FunzioneSingola) funzioneTMP).setVariable(funzioniOLD.get(i+1)); ((FunzioneAnteriore) funzioneTMP).setVariable(funzioniOLD.get(i+1));
funzioniOLD.set(i, funzioneTMP); funzioniOLD.set(i, funzioneTMP);
//è importante togliere prima gli elementi in fondo e poi quelli davanti, perché gli indici scalano da destra a sinistra. //è importante togliere prima gli elementi in fondo e poi quelli davanti, perché gli indici scalano da destra a sinistra.
funzioniOLD.remove(i+1); funzioniOLD.remove(i+1);
Utils.debug.println(debugSpaces+" •Set variable to expression:"+funzioneTMP.simbolo()); Utils.debug.println(debugSpaces+" •Set variable to expression:"+funzioneTMP.simbolo());
Utils.debug.println(debugSpaces+" "+"var="+((FunzioneSingola) funzioneTMP).getVariable().calcola()); Utils.debug.println(debugSpaces+" "+"var="+((FunzioneAnteriore) funzioneTMP).getVariable().calcola().toString());
} else { } else {
throw new java.lang.RuntimeException("Argomenti mancanti! Sistemare l'equazione!"); throw new java.lang.RuntimeException("Argomenti mancanti! Sistemare l'equazione!");
} }
@ -320,13 +507,14 @@ public class Parentesi extends FunzioneMultipla {
i++; i++;
n++; n++;
} }
} while (funzioniOLD.size() != before || fase != "somme"); } while (((funzioniOLD.size() != before || fase != "sistemi") && funzioniOLD.size() > 1));
setVariables(funzioniOLD); setVariables(funzioniOLD);
dsl = debugSpaces.length();debugSpaces = "";for (int i = 0; i < dsl-2; i++) {debugSpaces += " ";} dsl = debugSpaces.length();debugSpaces = "";for (int i = 0; i < dsl-2; i++) {debugSpaces += " ";}
Utils.debug.println(debugSpaces+"•Finished correcting classes."); Utils.debug.println(debugSpaces+"•Finished correcting classes.");
Utils.debug.println(debugSpaces+"•Result:"+calcola()); Termine result = calcola();
Utils.debug.println(debugSpaces+"•Result:"+result);
} }
} }
@ -335,13 +523,116 @@ public class Parentesi extends FunzioneMultipla {
return "Parentesi"; return "Parentesi";
} }
public ParteSistema calcolaSistema() throws Errore {
return new ParteSistema(calcolaEquazione());
}
public Equazione calcolaEquazione() throws Errore {
return new Equazione(calcola(), new Termine("0"));
}
@Override @Override
public Termine calcola() throws Errore { public Termine calcola() throws Errore {
Termine result = new Termine(BigSurdVec.ZERO); if (variables.length == 0) {
return new Termine("0");
} else if (variables.length == 1) {
return variables[0].calcola();
} else {
Termine result = new Termine("0");
for (Funzione f : variables) { for (Funzione f : variables) {
result = result.add(f.calcola()); result = result.add(f.calcola());
} }
return result; return result;
} }
}
@Override
public void draw(int x, int y, Display g, boolean small) {
if (parentesiIniziale && variables.length == 1) {
this.variables[0].draw(x, y, g, small);
} else {
float miny = y;
float maxy = y+getHeight(small);
int lw = Utils.getPlainTextWidth("(")+1;
int h = getHeight(small);
g.setColor(Color.BLACK);
if (small) {
g.draw45Line(x+3, y, x+2, y+1, true);
g.drawOrthoLine(x+2, y+1, x+2, y+h-2);
g.draw45Line(x+2, y+h-2, x+3, y+h-1, false);
} else {
g.draw45Line(x+3, y, x+1, y+2, true);
g.drawOrthoLine(x+1, y+2, x+1, y+h-3);
g.draw45Line(x+1, y+h-3, x+3, y+h-1, false);
}
x += lw;
for (Funzione f : variables) {
float fheight = f.getHeight(small);
float y2=miny+((maxy-miny)/2-fheight/2);
f.draw(x, (int) y2, g, small);
x+=f.getWidth();
}
if (small) {
g.draw45Line(x+1, y, x+2, y+1, false);
g.drawOrthoLine(x+2, y+1, x+2, y+h-2);
g.draw45Line(x+2, y+h-2, x+1, y+h-1, true);
} else {
g.draw45Line(x+1, y, x+3, y+2, false);
g.drawOrthoLine(x+3, y+2, x+3, y+h-3);
g.draw45Line(x+3, y+h-3, x+1, y+h-1, true);
}
}
}
@Override
public int getWidth() {
if (parentesiIniziale && variables.length == 1) {
return this.variables[0].getWidth();
} else {
int w = 0;
int lw = Utils.getPlainTextWidth("(")+1;
for (Funzione f : variables) {
w+=f.getWidth();
}
return w+lw*2;
}
}
@Override
public int getHeight(boolean small) {
if (parentesiIniziale && variables.length == 1) {
return this.variables[0].getHeight(small);
} else {
Funzione tmin = null;
Funzione tmax = null;
for (Funzione t : variables) {
if (tmin == null || t.getLine(small) >= tmin.getLine(small)) {
tmin = t;
}
if (tmax == null || t.getHeight(small) - t.getLine(small) >= tmax.getHeight(small) - tmax.getLine(small)) {
tmax = t;
}
}
if (tmin == null) return Utils.getFontHeight(small);
return tmin.getLine(small) + tmax.getHeight(small) - tmax.getLine(small);
}
}
@Override
public int getLine(boolean small) {
if (parentesiIniziale && variables.length == 1) {
return this.variables[0].getLine(small);
} else {
Funzione tl = null;
for (Funzione t : variables) {
if (tl == null || t.getLine(small) >= tl.getLine(small)) {
tl = t;
}
}
if (tl == null) return Utils.getFontHeight(small)/2;
return tl.getLine(small);
}
}
} }

View File

@ -1,5 +1,7 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import org.warp.engine.Display;
public class Potenza extends FunzioneDueValori { public class Potenza extends FunzioneDueValori {
public Potenza(Funzione value1, Funzione value2) { public Potenza(Funzione value1, Funzione value2) {
@ -15,4 +17,30 @@ public class Potenza extends FunzioneDueValori {
public Termine calcola() throws NumberFormatException, Errore { public Termine calcola() throws NumberFormatException, Errore {
return getVariable1().calcola().pow(getVariable2().calcola()); return getVariable1().calcola().pow(getVariable2().calcola());
} }
@Override
public void draw(int x, int y, Display g, boolean small) {
int dx = 0;
variable1.draw(dx+x, getHeight(small)-variable1.getHeight(small)+y, g, small);
dx+=variable1.getWidth()+1;
variable2.draw(dx+x, y, g, small);
}
@Override
public int getHeight(boolean small) {
return variable1.getHeight(small)+variable2.getHeight(true)-4;
}
@Override
public int getLine(boolean small) {
return variable2.getHeight(true)-4+variable1.getLine(small);
}
@Override
public int getWidth() {
int w1 = getVariable1().getWidth();
int w2 = getVariable2().getWidth();
return w1+1+w2;
}
} }

View File

@ -1,6 +1,7 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import org.nevec.rjm.BigSurdVec; import org.nevec.rjm.NumeroAvanzatoVec;
import org.warp.engine.Display;
public class Radice extends FunzioneDueValori { public class Radice extends FunzioneDueValori {
@ -15,8 +16,26 @@ public class Radice extends FunzioneDueValori {
@Override @Override
public Termine calcola() throws NumberFormatException, Errore { public Termine calcola() throws NumberFormatException, Errore {
Termine exponent = new Termine(BigSurdVec.ONE); Termine exponent = new Termine(NumeroAvanzatoVec.ONE);
exponent = exponent.divide(getVariable1().calcola()); exponent = exponent.divide(getVariable1().calcola());
return getVariable2().calcola().pow(exponent); return getVariable2().calcola().pow(exponent);
} }
@Override
public void draw(int x, int y, Display g, boolean small) {
// TODO Auto-generated method stub
}
@Override
public int getWidth() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getHeight(boolean small) {
// TODO Auto-generated method stub
return 0;
}
} }

View File

@ -1,8 +1,10 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import org.nevec.rjm.NumeroAvanzatoVec;
import org.nevec.rjm.Rational; import org.nevec.rjm.Rational;
import org.warp.engine.Display;
public class RadiceQuadrata extends FunzioneSingola { public class RadiceQuadrata extends FunzioneAnteriore {
public RadiceQuadrata(Funzione value) { public RadiceQuadrata(Funzione value) {
super(value); super(value);
@ -15,6 +17,30 @@ public class RadiceQuadrata extends FunzioneSingola {
@Override @Override
public Termine calcola() throws NumberFormatException, Errore { public Termine calcola() throws NumberFormatException, Errore {
return getVariable().calcola().pow(new Termine(Rational.ONE.divide(new Rational(2,1)))); Termine result = getVariable().calcola().pow(new Termine(new Rational(1,2)));
return result;
}
@Override
public void draw(int x, int y, Display g, boolean small) {
Utils.writeSquareRoot(g, getVariable(), x, y, small);
}
@Override
public int getWidth() {
return 5+getVariable().getWidth()+2;
}
@Override
public int getHeight(boolean small) {
int h1 = getVariable().getHeight(small)+2;
return h1;
}
@Override
public int getLine(boolean small) {
int h1 = getVariable().getLine(small)+2;
return h1;
} }
} }

View File

@ -4,13 +4,16 @@ import static org.warpgate.pi.calculator.Utils.concat;
public class Simboli { public class Simboli {
public static final String SUM = "+"; public static final String SUM = "+";
public static final String SUBTRACTION = "-";
public static final String MULTIPLICATION = "*"; public static final String MULTIPLICATION = "*";
public static final String DIVISION = "/"; public static final String DIVISION = "/";
public static final String NTH_ROOT = ""; public static final String NTH_ROOT = "";
public static final String SQUARE_ROOT = ""; public static final String SQUARE_ROOT = "";
public static final String PARENTHESIS_OPEN = "("; public static final String PARENTHESIS_OPEN = "(";
public static final String PARENTHESIS_CLOSE = ")"; public static final String PARENTHESIS_CLOSE = ")";
public static final String POTENZA = "^"; public static final String POTENZA = "";
public static final String EQUATION = "=";
public static final String SYSTEM = "{";
public static final String[] funzioni() { public static final String[] funzioni() {
return concat(funzioniNSN(), funzioniSN()); return concat(funzioniNSN(), funzioniSN());
@ -31,4 +34,10 @@ public class Simboli {
public static final String[] parentesi() { public static final String[] parentesi() {
return new String[]{PARENTHESIS_OPEN, PARENTHESIS_CLOSE}; return new String[]{PARENTHESIS_OPEN, PARENTHESIS_CLOSE};
} }
public static String[] incognite() {
return new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
}
public static String[] sintassiGenerale() {
return new String[]{SYSTEM, EQUATION};
}
} }

View File

@ -1,5 +1,11 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import java.awt.Color;
import java.math.BigInteger;
import org.nevec.rjm.NumeroAvanzatoVec;
import org.warp.engine.Display;
public class Somma extends FunzioneDueValori { public class Somma extends FunzioneDueValori {
public Somma(Funzione value1, Funzione value2) { public Somma(Funzione value1, Funzione value2) {
@ -13,7 +19,43 @@ public class Somma extends FunzioneDueValori {
@Override @Override
public Termine calcola() throws Errore { public Termine calcola() throws Errore {
return getVariable1().calcola().add(getVariable2().calcola()); Termine val1 = getVariable1().calcola();
Termine val2 = getVariable2().calcola();
Termine result = val1.add(val2);
return result;
} }
@Override
public void draw(int x, int y, Display g, boolean small) {
int ln = getLine(small);
int dx = 0;
variable1.draw(dx+x, ln-variable1.getLine(small)+y, g, small);
dx+=variable1.getWidth()+1;
try {
NumeroAvanzatoVec tm = variable2.calcola().getTerm();
Utils.writeLetter(g, simbolo(), dx+x, ln-Utils.getFontHeight(small)/2+y, small);
dx+=Utils.getPlainTextWidth(simbolo());
dx+=1;
} catch (Errore e) {
e.printStackTrace();
}
variable2.draw(dx+x, ln-variable2.getLine(small)+y, g, small);
}
@Override
public int getWidth() {
int dx = 0;
dx+=variable1.getWidth()+1;
try {
NumeroAvanzatoVec tm = variable2.calcola().getTerm();
dx+=Utils.getPlainTextWidth(simbolo());
dx+=1;
} catch (Errore e) {
e.printStackTrace();
}
return dx+=variable2.getWidth();
}
} }

View File

@ -1,56 +1,56 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import java.awt.Color;
import java.awt.Graphics;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.math.MathContext; import java.math.MathContext;
import java.util.ArrayList; import java.util.ArrayList;
import org.nevec.rjm.BigDecimalMath; import org.nevec.rjm.BigDecimalMath;
import org.nevec.rjm.BigSurd; import org.nevec.rjm.NumeroAvanzato;
import org.nevec.rjm.BigSurdVec; import org.nevec.rjm.NumeroAvanzatoVec;
import org.nevec.rjm.Rational; import org.nevec.rjm.Rational;
import org.warp.engine.Display;
import com.rits.cloning.Cloner;
public class Termine implements Funzione { public class Termine implements Funzione {
protected BigSurdVec term = BigSurdVec.ZERO; protected NumeroAvanzatoVec term = NumeroAvanzatoVec.ZERO;
protected ArrayList<VariabileEdEsponente> variables = new ArrayList<VariabileEdEsponente>();
public Termine(BigSurdVec val) { public Termine(NumeroAvanzatoVec val) {
term = val; term = val;
} }
public Termine(String s) { public Termine(String s) {
term = new BigSurdVec(new BigSurd(Utils.getRational(s), Rational.ONE)); term = new NumeroAvanzatoVec(new NumeroAvanzato(Utils.getRational(s), Rational.ONE));
} }
public Termine(Rational r) { public Termine(Rational r) {
term = new BigSurdVec(new BigSurd(r, Rational.ONE)); term = new NumeroAvanzatoVec(new NumeroAvanzato(r, Rational.ONE));
} }
public Termine(BigInteger r) { public Termine(BigInteger r) {
term = new BigSurdVec(new BigSurd(new Rational(r, BigInteger.ONE), Rational.ONE)); term = new NumeroAvanzatoVec(new NumeroAvanzato(new Rational(r, BigInteger.ONE), Rational.ONE));
} }
public Termine(BigDecimal r) { public Termine(BigDecimal r) {
term = new BigSurdVec(new BigSurd(Utils.getRational(r), Rational.ONE)); term = new NumeroAvanzatoVec(new NumeroAvanzato(Utils.getRational(r), Rational.ONE));
} }
public BigSurdVec getTerm() { public Termine(NumeroAvanzato numeroAvanzato) {
term = new NumeroAvanzatoVec(numeroAvanzato);
}
public NumeroAvanzatoVec getTerm() {
return term; return term;
} }
public void setTerm(BigSurdVec val) { public void setTerm(NumeroAvanzatoVec val) {
term = val; term = val;
} }
public ArrayList<VariabileEdEsponente> getVariables() {
return variables;
}
public void setVariables(ArrayList<VariabileEdEsponente> variables) {
this.variables = variables;
}
@Override @Override
public Termine calcola() { public Termine calcola() {
return this; return this;
@ -58,86 +58,321 @@ public class Termine implements Funzione {
@Override @Override
public String simbolo() { public String simbolo() {
return null; return toString();
} }
public Termine add(Termine f) throws Errore { public Termine add(Termine f) throws Errore {
Termine ret = new Termine(getTerm().add(f.getTerm())); Termine ret = new Termine(getTerm().add(f.getTerm()));
ret.setVariables(getVariables());
if (f.getVariables().size() > 0) {
System.err.println("Moltiplicazioni con variabili non implementato");
throw new Errore(Errori.NOT_IMPLEMENTED);
}
return ret; return ret;
} }
public Termine multiply(Termine f) throws Errore { public Termine multiply(Termine f) throws Errore {
Termine ret = new Termine(getTerm().multiply(f.getTerm())); Termine ret = new Termine(getTerm().multiply(f.getTerm()));
ret.setVariables(getVariables());
if (f.getVariables().size() > 0) {
System.err.println("Moltiplicazioni con variabili non implementato");
throw new Errore(Errori.NOT_IMPLEMENTED);
}
return ret; return ret;
} }
public Termine divide(Termine f) throws Errore { public Termine divide(Termine f) throws Errore {
Termine ret = new Termine(getTerm().divide(f.getTerm())); Termine ret = new Termine(getTerm().divide(f.getTerm()));
ret.setVariables(getVariables());
if (f.getVariables().size() > 0) {
System.err.println("Divisioni con variabili non implementato");
throw new Errore(Errori.NOT_IMPLEMENTED);
}
return ret; return ret;
} }
public Termine pow(Termine f) throws Errore { public Termine pow(Termine f) throws Errore {
Termine ret = new Termine(BigSurdVec.ONE); Termine ret = new Termine(NumeroAvanzatoVec.ONE);
if (f.getTerm().isBigInteger()) { if (f.getTerm().isBigInteger(true)) {
for (BigInteger i = BigInteger.ZERO; i.compareTo(f.getTerm().toBigInteger()) < 0; i = i.add(BigInteger.ONE)) { for (BigInteger i = BigInteger.ZERO; i.compareTo(f.getTerm().toBigInteger(true)) < 0; i = i.add(BigInteger.ONE)) {
ret = ret.multiply(new Termine(getTerm())); ret = ret.multiply(new Termine(getTerm()));
ret.setVariables(getVariables());
if (f.getVariables().size() > 0) {
System.err.println("Potenze con variabili non implementato");
throw new Errore(Errori.NOT_IMPLEMENTED);
} }
} } else if (getTerm().isRational(true) && f.getTerm().isRational(false) && f.getTerm().toRational(false).compareTo(Rational.HALF) == 0) {
} else if (getTerm().isRational() && f.getTerm().isRational() && f.getTerm().toRational().denom().compareTo(BigInteger.ONE) == 0) {
ret = new Termine(getTerm().toRational().pow(f.getTerm().toRational()));
ret.setVariables(getVariables());
if (f.getVariables().size() > 0) {
System.err.println("Potenze con variabili non implementato");
throw new Errore(Errori.NOT_IMPLEMENTED);
}
} else if (getTerm().isRational() && f.getTerm().isRational() && f.getTerm().toRational().compareTo(Rational.HALF) == 0) {
//Rational originalExponent = f.getTerm().toRational(); //Rational originalExponent = f.getTerm().toRational();
//Rational rootExponent = new Rational(originalExponent.denom(), originalExponent.numer()); //Rational rootExponent = new Rational(originalExponent.denom(), originalExponent.numer());
Rational numberToRoot = getTerm().toRational(); Rational numberToRoot = getTerm().toRational(true);
ret = new Termine(new BigSurdVec(new BigSurd(Rational.ONE, numberToRoot))); NumeroAvanzato na = new NumeroAvanzato(Rational.ONE, numberToRoot);
ret.setVariables(getVariables()); na = na.setIncognitex(getTerm().toNumeroAvanzato().getIncognitey().multiply(getTerm().toNumeroAvanzato().getIncognitez()));
if (f.getVariables().size() > 0) { na = na.setIncognitey(new Incognite());
System.err.println("Potenze con variabili non implementato"); na = na.setIncognitez(getTerm().toNumeroAvanzato().getIncognitez());
throw new Errore(Errori.NOT_IMPLEMENTED); ret = new Termine(na);
}
} else { } else {
ret = new Termine(BigDecimalMath.pow(getTerm().BigDecimalValue(new MathContext(Utils.scale, Utils.scaleMode2)), f.getTerm().BigDecimalValue(new MathContext(Utils.scale, Utils.scaleMode2)))); ret = new Termine(BigDecimalMath.pow(getTerm().BigDecimalValue(new MathContext(Utils.scale, Utils.scaleMode2)), f.getTerm().BigDecimalValue(new MathContext(Utils.scale, Utils.scaleMode2))));
ret.setVariables(getVariables());
if (f.getVariables().size() > 0) {
System.err.println("Potenze con variabili non implementato");
throw new Errore(Errori.NOT_IMPLEMENTED);
}
} }
return ret; return ret;
} }
@Override @Override
public String toString() { public String toString() {
if (getTerm().isBigInteger()) {
return getTerm().toBigInteger().toString();
} else if (getTerm().isRational()) {
return getTerm().toRational().toString();
} else {
return getTerm().toFancyString(); return getTerm().toFancyString();
} }
public void draw(int x, int y, Display g, boolean small, boolean drawMinus) {
boolean beforedrawminus = this.drawMinus;
this.drawMinus = drawMinus;
draw(x, y, g, small);
this.drawMinus = beforedrawminus;
}
private boolean drawMinus = true;
@Override
public void draw(int x, int y, Display g, boolean small) {
if (getTerm().isBigInteger(false)) {
String t = toString();
int w1 = Utils.getPlainTextWidth(t);
int h1 = Utils.getFontHeight(small);
if (t.startsWith("-")) {
if (drawMinus) {
} else {
int minusw = Utils.getPlainTextWidth("-");
int minush = Utils.getFontHeight(small);
t = t.substring(1);
} }
} }
Utils.writeLetter(g, t, x, y, small);
} else if (getTerm().isRational(false)) {
small = true;
Rational r = getTerm().toRational(false);
boolean minus = false;
int minusw = 0;
int minush = 0;
String numerator = r.numer().toString();
if (numerator.startsWith("-")) {
minus = true;
numerator = numerator.substring(1);
}
int w1 = Utils.getPlainTextWidth(numerator);
int h1 = Utils.getFontHeight(small);
int w2 = Utils.getPlainTextWidth(r.denom().toString());
int h2 = Utils.getFontHeight(small);
int maxw;
if (w1 > w2) {
maxw = 1+w1+1;
} else {
maxw = 1+w2+1;
}
if (minus) {
if (drawMinus) {
minusw = Utils.getPlainTextWidth("-");
minush = Utils.getFontHeight(small);
maxw += minusw;
Utils.writeLetter(g, "-", x, y+h1+1+1-(minush/2), small);
}
}
Utils.writeLetter(g, numerator, (int)(x+minusw+1+((double)(maxw-w1))/2d), y, small);
Utils.writeLetter(g, r.denom().toString(), (int)(x+minusw+1+((double)(maxw-w2))/2d), y+h1+1+1+1, small);
g.setColor(Color.BLACK);
g.fillRect(x+minusw+1, y+h1+1, maxw, 1);
} else if (getTerm().toFancyString().contains("/")) {
small = true;
String r = getTerm().toFancyString();
String numer = r.substring(0, r.lastIndexOf("/"));
String denom = r.substring(numer.length()+1, r.length());
if (numer.startsWith("(") && numer.endsWith(")")) {
numer = numer.substring(1, numer.length()-1);
}
boolean minus = false;
if (numer.startsWith("-")) {
minus = true;
numer = numer.substring(1);
}
int w1 = Utils.getPlainTextWidth(numer.toString());
int h1 = Utils.getFontHeight(small);
int w2 = Utils.getPlainTextWidth(denom.toString());
int h2 = Utils.getFontHeight(small);
int maxw;
if (w1 > w2) {
maxw = w1+2;
} else {
maxw = w2+2;
}
int minusw = 0;
int minush = 0;
if (minus) {
if (drawMinus) {
minusw = Utils.getPlainTextWidth("-")+1;
minush = Utils.getFontHeight(small);
maxw += minusw;
Utils.writeLetter(g, "-", x, y+h1+1+1-(minush/2), small);
}
}
Utils.writeLetter(g, numer, (int)(x+minusw+1+((double)(maxw-w1))/2d), y, small);
Utils.writeLetter(g, denom, (int)(x+minusw+1+((double)(maxw-w2))/2d), y+h1+1+1+1, small);
g.setColor(Color.BLACK);
g.fillRect(x+minusw+1, y+h1+1, maxw, 1);
} else {
String r = getTerm().toFancyString();
int w1 = Utils.getPlainTextWidth(r.toString());
int h1 = Utils.getFontHeight(small);
if (r.startsWith("-")) {
if (drawMinus) {
} else {
int minusw = Utils.getPlainTextWidth("-")+1;
int minush = Utils.getFontHeight(small);
r = r.substring(1);
}
}
Utils.writeLetter(g, r.toString(), x, y, small);
}
}
public int getHeight(boolean small, boolean drawMinus) {
boolean beforedrawminus = this.drawMinus;
this.drawMinus = drawMinus;
int h = getHeight(small);
this.drawMinus = beforedrawminus;
return h;
}
@Override
public int getHeight(boolean small) {
if (getTerm().isBigInteger(false)) {
int h1 = Utils.getFontHeight(small);
return h1;
} else if (getTerm().isRational(false)) {
small = true;
int h1 = Utils.getFontHeight(small);
int h2 = Utils.getFontHeight(small);
return h1+3+h2;
} else if (getTerm().toFancyString().contains("/")) {
small = true;
int h1 = Utils.getFontHeight(small);
int h2 = Utils.getFontHeight(small);
return h1+3+h2;
} else {
int h1 = Utils.getFontHeight(small);
return h1;
}
}
public int getWidth(boolean drawMinus) {
boolean beforedrawminus = this.drawMinus;
this.drawMinus = drawMinus;
int w = getWidth();
this.drawMinus = beforedrawminus;
return w;
}
@Override
public int getWidth() {
if (getTerm().isBigInteger(false)) {
String t = toString();
if (t.startsWith("-")) {
if (drawMinus) {
} else {
t = t.substring(1);
}
}
return Utils.getPlainTextWidth(t);
} else if (getTerm().isRational(false)) {
Rational r = getTerm().toRational(false);
boolean minus = false;
String numerator = r.numer().toString();
if (numerator.startsWith("-")) {
minus = true;
numerator = numerator.substring(1);
}
int w1 = Utils.getPlainTextWidth(numerator);
int w2 = Utils.getPlainTextWidth(r.denom().toString());
int maxw;
if (w1 > w2) {
maxw = 1+w1+1;
} else {
maxw = 1+w2+1;
}
if (minus) {
if (drawMinus) {
maxw += Utils.getPlainTextWidth("-");
}
}
return maxw+2;
} else if (getTerm().toFancyString().contains("/")) {
String r = getTerm().toFancyString();
String numer = r.substring(0, r.lastIndexOf("/"));
String denom = r.substring(numer.length()+1, r.length());
if (numer.startsWith("(") && numer.endsWith(")")) {
numer = numer.substring(1, numer.length()-1);
}
boolean minus = false;
if (numer.startsWith("-")) {
minus = true;
numer = numer.substring(1);
}
int w1 = Utils.getPlainTextWidth(numer.toString());
int w2 = Utils.getPlainTextWidth(denom.toString());
int maxw;
if (w1 > w2) {
maxw = w1+2;
} else {
maxw = w2+2;
}
if (minus) {
if (drawMinus) {
maxw += Utils.getPlainTextWidth("-");
}
}
return maxw+2;
} else {
String r = getTerm().toFancyString();
if (r.startsWith("-")) {
if (drawMinus) {
} else {
r = r.substring(1);
}
}
return Utils.getPlainTextWidth(r.toString());
}
}
public boolean soloIncognitaSemplice() {
if (this.getTerm().isBigInteger(true)) {
if (this.getTerm().toBigInteger(true).compareTo(BigInteger.ONE) == 0 && this.getTerm().toNumeroAvanzato().getIncognitey().count() > 0) {
return true;
}
}
return false;
}
@Override
public int getLine(boolean small) {
if (getTerm().isBigInteger(false)) {
return Utils.getFontHeight(small)/2;
} else if (getTerm().isRational(false)) {
small = true;
int h1 = Utils.getFontHeight(small);
return h1+1;
} else if (getTerm().toFancyString().contains("/")) {
small = true;
int h1 = Utils.getFontHeight(small);
return h1+1;
} else {
int h1 = Utils.getFontHeight(small);
return h1/2;
}
}
@Override
public Termine clone() {
Cloner cloner = new Cloner();
return cloner.deepClone(this);
}
/*
@Override
public void draw(int x, int y, Graphics g) {
}
@Override
public int getHeight() {
return Utils.getFontHeight();
}
@Override
public int getWidth() {
return 6*toString().length()-1;
}
*/
}

View File

@ -1,20 +1,30 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.StringWriter; import java.io.StringWriter;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.util.ArrayList; import java.util.ArrayList;
import org.nevec.rjm.BigDecimalMath; import org.nevec.rjm.BigDecimalMath;
import org.nevec.rjm.Rational; import org.nevec.rjm.Rational;
import org.warp.engine.Display;
import org.warp.engine.Display.Font;
public class Utils { public class Utils {
public static final int scale = 130; public static final int scale = 130;
public static final int resultScale = 8;
public static final int scaleMode = BigDecimal.ROUND_HALF_UP; public static final int scaleMode = BigDecimal.ROUND_HALF_UP;
public static final RoundingMode scaleMode2 = RoundingMode.HALF_UP; public static final RoundingMode scaleMode2 = RoundingMode.HALF_UP;
public static final Font fontBig = new Font("CalcBig", Font.PLAIN, 16);
public static final Font fontSmall = new Font("CalcSmall", Font.PLAIN, 16);
public static DebugStream debug = new DebugStream(); public static DebugStream debug = new DebugStream();
@ -69,19 +79,85 @@ public class Utils {
return c; return c;
} }
public static boolean ciSonoSoloNumeriESomme(ArrayList<Funzione> fl) { public static boolean ciSonoSoloFunzioniImpostateSommeEquazioniESistemi(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) { for (int i = 0; i < fl.size(); i++) {
if (!(fl.get(i) instanceof Termine || fl.get(i) instanceof Somma || fl.get(i) instanceof Parentesi)) { if (!(fl.get(i) instanceof Termine || fl.get(i) instanceof Somma || fl.get(i) instanceof Equazione || fl.get(i) instanceof ParteSistema || fl.get(i) instanceof Parentesi)) {
if (fl.get(i) instanceof FunzioneAnteriore) {
if (((FunzioneAnteriore)fl.get(i)).variable == null) {
return false; return false;
} }
} else if (fl.get(i) instanceof FunzioneDueValori) {
if (((FunzioneDueValori)fl.get(i)).variable1 == null || ((FunzioneDueValori)fl.get(i)).variable2 == null) {
return false;
}
} else {
return false;
}
}
}
return true;
}
public static boolean ciSonoSoloFunzioniImpostateSommeMoltiplicazioniEquazioniESistemi(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) {
if (!(fl.get(i) instanceof Termine || fl.get(i) instanceof Moltiplicazione || fl.get(i) instanceof Somma || fl.get(i) instanceof Equazione || fl.get(i) instanceof ParteSistema || fl.get(i) instanceof Parentesi)) {
if (fl.get(i) instanceof FunzioneAnteriore) {
if (((FunzioneAnteriore)fl.get(i)).variable == null) {
return false;
}
} else if (fl.get(i) instanceof FunzioneDueValori) {
if (((FunzioneDueValori)fl.get(i)).variable1 == null || ((FunzioneDueValori)fl.get(i)).variable2 == null) {
return false;
}
} else {
return false;
}
}
}
return true;
}
public static boolean ciSonoSoloFunzioniImpostateEquazioniESistemi(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) {
if (!(fl.get(i) instanceof Termine || fl.get(i) instanceof Equazione || fl.get(i) instanceof ParteSistema || fl.get(i) instanceof Parentesi)) {
if (fl.get(i) instanceof FunzioneAnteriore) {
if (((FunzioneAnteriore)fl.get(i)).variable == null) {
return false;
}
} else if (fl.get(i) instanceof FunzioneDueValori) {
if (((FunzioneDueValori)fl.get(i)).variable1 == null || ((FunzioneDueValori)fl.get(i)).variable2 == null) {
return false;
}
} else {
return false;
}
}
}
return true;
}
public static boolean ciSonoSoloFunzioniImpostateESistemi(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) {
if (!(fl.get(i) instanceof Termine || fl.get(i) instanceof Equazione || fl.get(i) instanceof ParteSistema || fl.get(i) instanceof Parentesi)) {
if (fl.get(i) instanceof FunzioneAnteriore) {
if (((FunzioneAnteriore)fl.get(i)).variable == null) {
return false;
}
} else if (fl.get(i) instanceof FunzioneDueValori) {
if (((FunzioneDueValori)fl.get(i)).variable1 == null || ((FunzioneDueValori)fl.get(i)).variable2 == null) {
return false;
}
} else {
return false;
}
}
} }
return true; return true;
} }
public static boolean ciSonoFunzioniSNnonImpostate(ArrayList<Funzione> fl) { public static boolean ciSonoFunzioniSNnonImpostate(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) { for (int i = 0; i < fl.size(); i++) {
if (fl.get(i) instanceof FunzioneSingola) { if (fl.get(i) instanceof FunzioneAnteriore && !(fl.get(i) instanceof ParteSistema)) {
if (((FunzioneSingola)fl.get(i)).variable == null) { if (((FunzioneAnteriore)fl.get(i)).variable == null) {
return true; return true;
} }
} }
@ -89,12 +165,77 @@ public class Utils {
return false; return false;
} }
public static boolean ciSonoAltreFunzioni(ArrayList<Funzione> fl) { public static boolean ciSonoFunzioniNSNnonImpostate(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) { for (int i = 0; i < fl.size(); i++) {
if (!(fl.get(i) instanceof Termine || fl.get(i) instanceof Somma || fl.get(i) instanceof Parentesi || fl.get(i) instanceof FunzioneSingola || fl.get(i) instanceof Moltiplicazione || fl.get(i) instanceof Divisione)) { if (fl.get(i) instanceof FunzioneDueValori && !(fl.get(i) instanceof Equazione) && !(fl.get(i) instanceof Somma) && !(fl.get(i) instanceof Sottrazione) && !(fl.get(i) instanceof Moltiplicazione) && !(fl.get(i) instanceof Divisione)) {
if (((FunzioneDueValori)fl.get(i)).variable1 == null && ((FunzioneDueValori)fl.get(i)).variable2 == null) {
return true; return true;
} }
} }
}
return false;
}
public static boolean ciSonoMoltiplicazioniNonImpostate(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) {
if (fl.get(i) instanceof Moltiplicazione || fl.get(i) instanceof Divisione) {
if (((FunzioneDueValori)fl.get(i)).variable1 == null && ((FunzioneDueValori)fl.get(i)).variable2 == null) {
return true;
}
}
}
return false;
}
public static boolean ciSonoSommeNonImpostate(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) {
if (fl.get(i) instanceof Somma) {
if (((FunzioneDueValori)fl.get(i)).variable1 == null && ((FunzioneDueValori)fl.get(i)).variable2 == null) {
return true;
}
}
}
return false;
}
public static boolean ciSonoEquazioniNonImpostate(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) {
if (fl.get(i) instanceof Equazione) {
if (((FunzioneDueValori)fl.get(i)).variable1 == null && ((FunzioneDueValori)fl.get(i)).variable2 == null) {
return true;
}
}
}
return false;
}
public static boolean ciSonoSistemiNonImpostati(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) {
if (fl.get(i) instanceof ParteSistema) {
if (((ParteSistema)fl.get(i)).variable == null) {
return true;
}
}
}
return false;
}
public static boolean ciSonoAltreFunzioniImpostate(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) {
if (!(fl.get(i) instanceof Termine || fl.get(i) instanceof Somma || fl.get(i) instanceof Parentesi || fl.get(i) instanceof FunzioneAnteriore || fl.get(i) instanceof Moltiplicazione || fl.get(i) instanceof Divisione)) {
if (fl.get(i) instanceof FunzioneAnteriore) {
if (((FunzioneAnteriore)fl.get(i)).variable == null) {
return true;
}
} else if (fl.get(i) instanceof FunzioneDueValori) {
if (((FunzioneDueValori)fl.get(i)).variable1 == null || ((FunzioneDueValori)fl.get(i)).variable2 == null) {
return true;
}
} else {
return true;
}
}
}
return false; return false;
} }
@ -106,6 +247,10 @@ public class Utils {
try { try {
return new Rational(str); return new Rational(str);
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
if (new BigDecimal(str).compareTo(new BigDecimal(Double.MAX_VALUE)) < 0 && new BigDecimal(str).compareTo(new BigDecimal(Double.MIN_VALUE)) > 0) {
if (str.equals("-")) {
str = "-1";
}
long bits = Double.doubleToLongBits(Double.parseDouble(str)); long bits = Double.doubleToLongBits(Double.parseDouble(str));
long sign = bits >>> 63; long sign = bits >>> 63;
@ -133,19 +278,27 @@ public class Utils {
b = 1; b = 1;
} }
return new Rational(new BigInteger(a+""),new BigInteger(b+"")); return new Rational(new BigInteger(a+""),new BigInteger(b+""));
} else {
BigDecimal original = new BigDecimal(str);
BigInteger numerator = original.unscaledValue();
BigInteger denominator = BigDecimalMath.pow(BigDecimal.TEN, new BigDecimal(original.scale())).toBigIntegerExact();
return new Rational(numerator, denominator);
}
} }
} }
public static BigDecimal rationalToIrrationalString(Rational r) { public static BigDecimal rationalToIrrationalString(Rational r) {
return BigDecimalMath.divideRound(new BigDecimal(r.numer()).setScale(Utils.scale, Utils.scaleMode), new BigDecimal(r.denom()).setScale(Utils.scale, Utils.scaleMode)); return BigDecimalMath.divideRound(new BigDecimal(r.numer()).setScale(Utils.scale, Utils.scaleMode), new BigDecimal(r.denom()).setScale(Utils.scale, Utils.scaleMode));
} }
public static boolean variabiliUguali(ArrayList<VariabileEdEsponente> variables, ArrayList<VariabileEdEsponente> variables2) { public static boolean variabiliUguali(ArrayList<Incognita> variables, ArrayList<Incognita> variables2) {
if (variables.size() != variables2.size()) { if (variables.size() != variables2.size()) {
return false; return false;
} else { } else {
for (VariabileEdEsponente v : variables) { for (Incognita v : variables) {
if (!variables2.contains(v)) { if (!variables2.contains(v)) {
return false; return false;
} }
@ -153,4 +306,61 @@ public class Utils {
return true; return true;
} }
} }
public static void writeLetter(Display d, String text, int x, int y, boolean small) {
if (small) {
d.setFont(fontSmall);
} else {
d.setFont(fontBig);
}
d.setColor(Color.BLACK);
d.drawString(text, x, y+getFontHeight(small));
}
public static void writeSquareRoot(Display g, Funzione var, int x, int y, boolean small) {
if (small) {
g.setFont(fontSmall);
} else {
g.setFont(fontBig);
}
g.setColor(Color.BLACK);
int w1 = var.getWidth();
int h1 = var.getHeight(small);
int wsegno = 5;
int hsegno = h1+2;
var.draw(x+wsegno, y+(hsegno-h1), g, small);
g.draw45Line(x, y+hsegno-3, x+2, y+hsegno-1, false);
g.drawOrthoLine(x+2, y+(hsegno-1)/2+1, x+2, y+hsegno-1);
g.drawOrthoLine(x+3, y, x+3, y+(hsegno-1)/2);
g.drawOrthoLine(x+3, y, x+3+1+w1+2, y);
}
public static final int getPlainTextWidth(String text) {
Graphics graphics = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).getGraphics();
// get metrics from the graphics
FontMetrics metrics = graphics.getFontMetrics(fontBig.getFontAwt());
// get the advance of my text in this font
// and render context
int adv = metrics.stringWidth(text);
// calculate the size of a box to hold the
// text with some padding.
if (adv > 0) {
adv-=1;
}
return adv;
}
public static final int getFontHeight() {
return getFontHeight(false);
}
public static final int getFontHeight(boolean small) {
if (small) {
return 6;
} else {
return 9;
}
}
} }

View File

@ -1,25 +0,0 @@
package org.warpgate.pi.calculator;
import java.math.BigInteger;
public class VariabileEdEsponente {
public char simbolo = 'X';
public BigInteger esponente = BigInteger.ONE;
public VariabileEdEsponente(char simbolo, BigInteger esponente) {
this.simbolo = simbolo;
this.esponente = esponente;
}
@Override
public boolean equals(Object o) {
if (o instanceof VariabileEdEsponente) {
if (this.simbolo == ((VariabileEdEsponente) o).simbolo) {
if (this.esponente == ((VariabileEdEsponente) o).esponente) {
return true;
}
}
}
return false;
}
}