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

@ -1,6 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-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 kind="output" path="bin"/> <classpathentry combineaccessrules="false" kind="src" path="/New2DGame"/>
</classpath> <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"/>
</classpath>

25
.gitignore vendored
View File

@ -1,12 +1,13 @@
*.class *.class
# Mobile Tools for Java (J2ME) # Mobile Tools for Java (J2ME)
.mtj.tmp/ .mtj.tmp/
# Package Files # # Package Files #
*.jar *.jar
*.war *.war
*.ear *.ear
# 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,8 +1,10 @@
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/warpgate/pi/calculator/Main.java=UTF-8 encoding//src/org/nevec/rjm/NumeroAvanzato.java=UTF-8
encoding//src/org/warpgate/pi/calculator/Parentesi.java=UTF-8 encoding//src/org/nevec/rjm/NumeroAvanzatoVec.java=UTF-8
encoding//src/org/warpgate/pi/calculator/Radice.java=UTF-8 encoding//src/org/warpgate/pi/calculator/Main.java=UTF-8
encoding//src/org/warpgate/pi/calculator/RadiceQuadrata.java=UTF-8 encoding//src/org/warpgate/pi/calculator/Parentesi.java=UTF-8
encoding//src/org/warpgate/pi/calculator/Simboli.java=UTF-8 encoding//src/org/warpgate/pi/calculator/Radice.java=UTF-8
encoding//src/org/warpgate/pi/calculator/RadiceQuadrata.java=UTF-8
encoding//src/org/warpgate/pi/calculator/Simboli.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 ;
normalize() ; try {
normalizeG() ; normalize() ;
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);
normalize(); try {
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;
return diff.signum(); try {
diff = this.subtract(oth);
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("");
compute(); try {
compute();
} catch (Errore e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} }
} /* actionPerformed */ } /* actionPerformed */

View File

@ -1,36 +1,36 @@
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 {
public Calculator(boolean b) { public Calculator(boolean b) {
Utils.debugOn = b; Utils.debugOn = b;
} }
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();
} }
public RisultatoEquazione calcolaequazione(String string) throws Errore { public RisultatoEquazione calcolaequazione(String string) throws Errore {
if (string.split("=").length == 0) { if (string.split("=").length == 0) {
return new RisultatoEquazione(new Termine("0"), true); return new RisultatoEquazione(new Termine("0"), true);
} }
if (string.split("=").length <= 2) { if (string.split("=").length <= 2) {
if (string.split("=").length == 1) { if (string.split("=").length == 1) {
string = string + "=0"; string = string + "=0";
} }
Termine res1 = calcolarisultato(string.split("=")[0]); Termine res1 = calcolarisultato(string.split("=")[0]);
Termine res2 = calcolarisultato(string.split("=")[1]); Termine res2 = calcolarisultato(string.split("=")[1]);
Termine res = res1.add(res2.multiply(new Termine("-1"))); Termine res = res1.add(res2.multiply(new Termine("-1")));
if (res.calcola().getTerm().toString().equals("0")) { if (res.calcola().getTerm().toString().equals("0")) {
return new RisultatoEquazione(res.calcola(), true); return new RisultatoEquazione(res.calcola(), true);
} }
return new RisultatoEquazione(res.calcola(), false); return new RisultatoEquazione(res.calcola(), false);
} }
return new RisultatoEquazione(null, false); return new RisultatoEquazione(null, false);
} }
} }

View File

@ -1,23 +1,169 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import org.nevec.rjm.BigSurdVec; import java.awt.Color;
import java.awt.Graphics;
public class Divisione extends FunzioneDueValori {
import org.nevec.rjm.NumeroAvanzatoVec;
public Divisione(Funzione value1, Funzione value2) { import org.nevec.rjm.Rational;
super(value1, value2); import org.warp.engine.Display;
}
public class Divisione extends FunzioneDueValori {
@Override
public String simbolo() { public Divisione(Funzione value1, Funzione value2) {
return Simboli.DIVISION; super(value1, value2);
} }
@Override @Override
public Termine calcola() throws Errore { public String simbolo() {
if (getVariable2().calcola().getTerm().compareTo(BigSurdVec.ZERO) == 0) { return Simboli.DIVISION;
throw new Errore(Errori.DIVISION_BY_ZERO); }
}
return getVariable1().calcola().divide(getVariable2().calcola()); @Override
} public Termine calcola() throws Errore {
if (variable2 == null || variable1 == null) {
return new Termine("0");
}
if (variable2.calcola().getTerm().compareTo(NumeroAvanzatoVec.ZERO) == 0) {
throw new Errore(Errori.DIVISION_BY_ZERO);
}
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

@ -1,8 +1,13 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
public enum Errori { 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;
public interface Funzione { import org.warp.engine.Display;
public String simbolo();
public Termine calcola() throws Errore; import com.rits.cloning.Cloner;
}
public interface Funzione {
public String simbolo();
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,28 +1,92 @@
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;
public abstract class FunzioneDueValori implements Funzione {
public FunzioneDueValori(Funzione value1, Funzione value2) { import com.rits.cloning.Cloner;
setVariable1(value1);
setVariable2(value2); public abstract class FunzioneDueValori implements Funzione {
} public FunzioneDueValori(Funzione value1, Funzione value2) {
protected Funzione variable1 = new Termine(Rational.ZERO); setVariable1(value1);
public Funzione getVariable1() { setVariable2(value2);
return variable1; }
} protected Funzione variable1 = new Termine(Rational.ZERO);
public void setVariable1(Funzione value) { public Funzione getVariable1() {
variable1 = value; return variable1;
} }
protected Funzione variable2 = new Termine(Rational.ZERO); public void setVariable1(Funzione value) {
public Funzione getVariable2() { variable1 = value;
return variable2; }
} protected Funzione variable2 = new Termine(Rational.ZERO);
public void setVariable2(Funzione value) { public Funzione getVariable2() {
variable2 = value; return variable2;
} }
@Override public void setVariable2(Funzione value) {
public abstract String simbolo(); variable2 = value;
@Override }
public abstract Termine calcola() throws Errore; @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 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

@ -1,54 +1,71 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public abstract class FunzioneMultipla implements Funzione { import com.rits.cloning.Cloner;
public FunzioneMultipla() {
setVariables(new Funzione[]{}); public abstract class FunzioneMultipla implements Funzione {
} public FunzioneMultipla() {
public FunzioneMultipla(Funzione[] values) { setVariables(new Funzione[]{});
setVariables(values); }
} public FunzioneMultipla(Funzione[] values) {
protected Funzione[] variables; setVariables(values);
public Funzione[] getVariables() { }
return variables; protected Funzione[] variables;
} public Funzione[] getVariables() {
public void setVariables(Funzione[] value) { return variables;
variables = value; }
} public void setVariables(Funzione[] value) {
public void setVariables(final List<Funzione> value) { variables = value;
int vsize = value.size(); }
Funzione[] tmp = new Funzione[vsize]; public void setVariables(final List<Funzione> value) {
for (int i = 0; i < vsize; i++) { int vsize = value.size();
tmp[i] = value.get(i); Funzione[] tmp = new Funzione[vsize];
} for (int i = 0; i < vsize; i++) {
variables = tmp; tmp[i] = value.get(i);
} }
variables = tmp;
public Funzione getVariable(int index) { }
return variables[index];
} public Funzione getVariable(int index) {
public void setVariable(int index, Funzione value) { return variables[index];
variables[index] = value; }
} public void setVariable(int index, Funzione value) {
variables[index] = value;
public void addVariableToEnd(Funzione value) { }
int index = variables.length;
setVariablesLength(index+1); public void addVariableToEnd(Funzione value) {
variables[index] = value; int index = variables.length;
} setVariablesLength(index+1);
variables[index] = value;
public int getVariablesLength() { }
return variables.length;
} public int getVariablesLength() {
return variables.length;
public void setVariablesLength(int length) { }
variables = Arrays.copyOf(variables, length);
} public void setVariablesLength(int length) {
variables = Arrays.copyOf(variables, length);
@Override }
public abstract String simbolo();
@Override @Override
public abstract Termine calcola() throws Errore; public abstract String simbolo();
} @Override
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,27 +1,216 @@
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;
try { import java.awt.Graphics2D;
long start = System.nanoTime(); import java.awt.image.BufferStrategy;
Termine result = c.calcolarisultato("((5^2+3√(100/0.1))*Ⓐ7+9/15*2√(26/2))/21"); import java.awt.image.BufferedImage;
long end = System.nanoTime(); import java.io.File;
long timeElapsed = end-start; import java.io.IOException;
System.out.println("RESULT: " + result);
System.out.println("DECIMAl RESULT: " + result.getTerm().toBigDecimal()); import javax.imageio.ImageIO;
System.out.println("Time elapsed: " + (double) timeElapsed / 1000000000 + "\n");
import org.gatecraft.game2d.utils.BitmapImage;
import org.nevec.rjm.NumeroAvanzato;
start = System.nanoTime(); import org.nevec.rjm.NumeroAvanzatoVec;
RisultatoEquazione eresult = c.calcolaequazione("((5^2+3√(100/0.1))*Ⓐ7+9/15*2√(26/2))/21=(175*(2√7)+3*(2√13))/105"); import org.nevec.rjm.Rational;
end = System.nanoTime(); import org.warp.engine.ActionInterface;
timeElapsed = end-start; import org.warp.engine.Display;
System.out.println("Is an equation: " + eresult.isAnEquation); import javafx.animation.KeyFrame;
System.out.println("L-R: " + eresult.LR); import javafx.animation.Timeline;
System.out.println("Time elapsed: " + (((double) timeElapsed / 1000000000)) + "\n"); import javafx.event.Event;
} catch (Errore e) { import javafx.event.EventHandler;
System.err.println(e.id); 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 {
//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();
Termine result = c.calcolarisultato("((5^2+3√(100/0.1))*Ⓐ7+9/15*2√(26/2))/21");
long end = System.nanoTime();
long timeElapsed = end-start;
System.out.println("RESULT: " + result);
System.out.println("DECIMAl RESULT: " + result.getTerm().toBigDecimal());
System.out.println("Time elapsed: " + (double) timeElapsed / 1000000000 + "\n");
start = System.nanoTime();
RisultatoEquazione eresult = c.calcolaequazione("((5^2+3√(100/0.1))*Ⓐ7+9/15*2√(26/2))/21=(175*(2√7)+3*(2√13))/105");
end = System.nanoTime();
timeElapsed = end-start;
System.out.println("Is an equation: " + eresult.isAnEquation);
System.out.println("L-R: " + eresult.LR);
System.out.println("Time elapsed: " + (((double) timeElapsed / 1000000000)) + "\n");
*/
} 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);
}
}
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,18 +1,84 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
public class Moltiplicazione extends FunzioneDueValori { import java.awt.Graphics;
import java.math.BigInteger;
public Moltiplicazione(Funzione value1, Funzione value2) {
super(value1, value2); import org.nevec.rjm.NumeroAvanzatoVec;
}
public class Moltiplicazione extends FunzioneDueValori {
@Override
public String simbolo() { public Moltiplicazione(Funzione value1, Funzione value2) {
return Simboli.MULTIPLICATION; super(value1, value2);
} }
@Override @Override
public Termine calcola() throws Errore { public String simbolo() {
return getVariable1().calcola().multiply(getVariable2().calcola()); return Simboli.MULTIPLICATION;
} }
@Override
public Termine calcola() throws Errore {
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

@ -1,347 +1,638 @@
package org.warpgate.pi.calculator; 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.util.ArrayList; import java.awt.Color;
import java.util.regex.Matcher; import java.util.ArrayList;
import java.util.regex.Pattern; import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.nevec.rjm.BigSurdVec;
import org.nevec.rjm.NumeroAvanzato;
public class Parentesi extends FunzioneMultipla { import org.nevec.rjm.NumeroAvanzatoVec;
import org.warp.engine.Display;
public Parentesi() {
super(); public class Parentesi extends FunzioneMultipla {
}
public Parentesi() {
public Parentesi(Funzione[] values) { super();
super(values); }
}
public Parentesi(Funzione[] values) {
public Parentesi(String string, String debugSpaces) throws Errore { super(values);
super(); }
try{
//Se l'espressione è già un numero: private boolean parentesiIniziale = false;
setVariables(new Funzione[]{new Termine(string)});
Utils.debug.println(debugSpaces+"•Result:"+string); public Parentesi(String string) throws Errore {
} catch (NumberFormatException ex) { this(string, "", true);
String processExpression = string; }
Utils.debug.println(debugSpaces+"•Analyzing expression:"+processExpression); public Parentesi(String string, String debugSpaces, boolean parentesiIniziale) throws Errore {
debugSpaces+= " "; super();
this.parentesiIniziale = parentesiIniziale;
//Se l'espressione non è già un numero: try{
//Se l'espressione è già un numero:
//Correggi i segni ++ e -- in eccesso setVariables(new Funzione[]{new Termine(string)});
Pattern pattern = Pattern.compile("\\+\\++?|\\-\\-+?"); Utils.debug.println(debugSpaces+"•(Value:"+string+")");
Matcher matcher = pattern.matcher(processExpression); } catch (NumberFormatException ex) {
boolean cambiati = false; String processExpression = string;
while (matcher.find()) {
cambiati = true; Utils.debug.println(debugSpaces+"•Analyzing expression:"+processExpression);
String correzione = "+"; debugSpaces+= " ";
processExpression = processExpression.substring(0, matcher.start(0)+1)+correzione+processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length());
matcher = pattern.matcher(processExpression); //Se l'espressione non è già un numero:
}
//Controlla se ci sono più di un uguale
//Correggi i segni +- e -+ in eccesso int equationsFound = 0;
pattern = Pattern.compile("\\+\\-|\\-\\+"); int systemsFound = 0;
matcher = pattern.matcher(processExpression); for (char c : processExpression.toCharArray()) {
while (matcher.find()) { if ((""+c).equals(Simboli.EQUATION)) {
cambiati = true; equationsFound+=1;
String correzione = "-"; }
processExpression = processExpression.substring(0, matcher.start(0)+1)+correzione+processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length()); if ((""+c).equals(Simboli.SYSTEM)) {
matcher = pattern.matcher(processExpression); equationsFound+=1;
} }
}
//Rimuovi i segni appena dopo le parentesi if (equationsFound == 1 && systemsFound == 0) {
if (processExpression.contains("(+")) { processExpression = Simboli.SYSTEM+processExpression;
cambiati = true; systemsFound+=1;
processExpression = processExpression.replace("(+", "("); }
} if (equationsFound != systemsFound) {
//Rimuovi i segni appena dopo l'inizio throw new Errore(Errori.SYNTAX_ERROR);
if (processExpression.startsWith("+")) { }
cambiati = true;
processExpression = processExpression.substring(1, processExpression.length()); //Correggi i segni ++ e -- in eccesso
} Pattern pattern = Pattern.compile("\\+\\++?|\\-\\-+?");
Matcher matcher = pattern.matcher(processExpression);
//Rimuovi i + in eccesso boolean cambiati = false;
pattern = Pattern.compile("["+ while (matcher.find()) {
ArrayToRegex(Utils.add(concat(Simboli.segni(true), Simboli.funzioni()), "(")) cambiati = true;
+"]\\+[^"+ String correzione = "+";
ArrayToRegex(concat(concat(Simboli.segni(true), Simboli.funzioni()), new String[]{"(", ")"})) processExpression = processExpression.substring(0, matcher.start(0)+1)+correzione+processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length());
+"]+?["+ matcher = pattern.matcher(processExpression);
ArrayToRegex(concat(Simboli.segni(true), Simboli.funzioni())) }
+"]|["+
ArrayToRegex(concat(Simboli.segni(true), Simboli.funzioni())) //Correggi i segni +- e -+ in eccesso
+"]+?\\+[^"+ pattern = Pattern.compile("\\+\\-|\\-\\+");
ArrayToRegex(concat(concat(Simboli.segni(true), Simboli.funzioni()), new String[]{"(", ")"})) matcher = pattern.matcher(processExpression);
+"]"); while (matcher.find()) {
matcher = pattern.matcher(processExpression); cambiati = true;
cambiati = false; String correzione = "-";
while (matcher.find()) { processExpression = processExpression.substring(0, matcher.start(0))+correzione+processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length());
cambiati = true; matcher = pattern.matcher(processExpression);
String correzione = matcher.group(0).replaceFirst(Matcher.quoteReplacement("+"), ""); }
processExpression = processExpression.substring(0, matcher.start(0)+1)+correzione+processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length());
matcher = pattern.matcher(processExpression); //Rimuovi i segni appena dopo le parentesi
} if (processExpression.contains("(+")) {
cambiati = true;
//Correggi i segni - in +- processExpression = processExpression.replace("(+", "(");
pattern = Pattern.compile("[^"+Utils.ArrayToRegex(concat(concat(Simboli.funzioni(),Simboli.parentesi()), Simboli.segni(true)))+"]-"); }
matcher = pattern.matcher(processExpression);
while (matcher.find()) { //Cambia i segni appena prima le parentesi
cambiati = true; if (processExpression.contains("-(")) {
String correzione = "+-"; cambiati = true;
processExpression = processExpression.substring(0, matcher.start(0)+1)+correzione+processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length()); processExpression = processExpression.replace("-(", "-1*(");
matcher = pattern.matcher(processExpression); }
} //Rimuovi i segni appena dopo l'inizio
if (processExpression.startsWith("+")) {
if (cambiati) { cambiati = true;
Utils.debug.println(debugSpaces+"•Resolved signs:"+processExpression); processExpression = processExpression.substring(1, processExpression.length());
} }
//Aggiungi i segni * accanto alle parentesi //Rimuovi i + in eccesso
pattern = Pattern.compile("\\([^\\(]+?\\)"); pattern = Pattern.compile("["+
matcher = pattern.matcher(processExpression); ArrayToRegex(Utils.add(concat(Simboli.segni(true), Simboli.funzioni()), "("))
cambiati = false; +"]\\+[^"+
while (matcher.find()) { ArrayToRegex(concat(concat(Simboli.segni(true), Simboli.funzioni()), new String[]{"(", ")"}))
cambiati = true; +"]+?["+
//sistema i segni * impliciti prima e dopo l'espressione. ArrayToRegex(concat(Simboli.segni(true), Simboli.funzioni()))
String beforeexp = processExpression.substring(0, matcher.start(0)); +"]|["+
String newexp = matcher.group(0).substring(1, matcher.group(0).length()-1); ArrayToRegex(concat(Simboli.segni(true), Simboli.funzioni()))
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()) { ArrayToRegex(concat(concat(Simboli.segni(true), Simboli.funzioni()), new String[]{"(", ")"}))
//Se la stringa precedente finisce con un numero +"]");
beforeexp += "*"; matcher = pattern.matcher(processExpression);
} cambiati = false;
if (Pattern.compile("^[^"+Utils.ArrayToRegex(Utils.add(concat(Simboli.funzioni(), Simboli.segni(true)), ")"))+"]").matcher(afterexp).find()) { while (matcher.find()) {
//Se la stringa successiva inizia con un numero cambiati = true;
afterexp = "*"+afterexp; String correzione = matcher.group(0).replaceFirst(Matcher.quoteReplacement("+"), "");
} processExpression = processExpression.substring(0, matcher.start(0)+1)+correzione+processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length());
processExpression = beforeexp+""+newexp+""+afterexp; matcher = pattern.matcher(processExpression);
matcher = pattern.matcher(processExpression); }
}
//Correggi i segni - in +-
processExpression = processExpression.replace("", "(").replace("", ")"); pattern = Pattern.compile("[^"+Utils.ArrayToRegex(concat(concat(Simboli.funzioni(),new String[]{Simboli.PARENTHESIS_OPEN}), Simboli.segni(true)))+"]-");
matcher = pattern.matcher(processExpression);
if (cambiati) { while (matcher.find()) {
Utils.debug.println(debugSpaces+"•Added implicit multiplications:"+processExpression); cambiati = true;
} String correzione = "+-";
processExpression = processExpression.substring(0, matcher.start(0)+1)+correzione+processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length());
Utils.debug.println(debugSpaces+"•Subdivision in classes:"); matcher = pattern.matcher(processExpression);
}
debugSpaces += " ";
if (cambiati) {
Utils.debug.println(debugSpaces+"•Resolved signs:"+processExpression);
//Suddividi tutto }
Parentesi parentesiNonSuddivisaCorrettamente = new Parentesi();
parentesiNonSuddivisaCorrettamente.setVariables(new Funzione[]{}); //Aggiungi i segni * accanto alle parentesi
String tmp = ""; pattern = Pattern.compile("\\([^\\(]+?\\)");
final String[] funzioni = concat(concat(Simboli.funzioni(), Simboli.parentesi()), Simboli.segni(true)); matcher = pattern.matcher(processExpression);
for (int i = 0; i < processExpression.length(); i++) { cambiati = false;
//Per ogni carattere cerca se è un numero o una funzione: while (matcher.find()) {
String charI = processExpression.charAt(i)+""; cambiati = true;
if (Utils.isInArray(charI, funzioni)) { //sistema i segni * impliciti prima e dopo l'espressione.
String beforeexp = processExpression.substring(0, matcher.start(0));
//Cerca il tipo di funzione tra le esistenti String newexp = matcher.group(0).substring(1, matcher.group(0).length()-1);
Funzione f = null; String afterexp = processExpression.substring(matcher.start(0)+matcher.group(0).length(), processExpression.length());
switch (charI) { if (Pattern.compile("[^\\-"+Utils.ArrayToRegex(Utils.add(concat(Simboli.funzioni(), concat(Simboli.segni(true), Simboli.sintassiGenerale())), "("))+"]$").matcher(beforeexp).find()) {
case Simboli.SUM: //Se la stringa precedente finisce con un numero
f = new Somma(null, null); beforeexp += Simboli.MULTIPLICATION;
break; }
case Simboli.MULTIPLICATION: if (Pattern.compile("^[^\\-"+Utils.ArrayToRegex(Utils.add(concat(Simboli.funzioni(), concat(Simboli.segni(true), Simboli.sintassiGenerale())), ")"))+"]").matcher(afterexp).find()) {
f = new Moltiplicazione(null, null); //Se la stringa successiva inizia con un numero
break; afterexp = Simboli.MULTIPLICATION+afterexp;
case Simboli.DIVISION: }
f = new Divisione(null, null); processExpression = beforeexp+""+newexp+""+afterexp;
break; matcher = pattern.matcher(processExpression);
case Simboli.NTH_ROOT: }
f = new Radice(null, null);
break; processExpression = processExpression.replace("", "(").replace("", ")");
case Simboli.SQUARE_ROOT:
f = new RadiceQuadrata(null); if (cambiati) {
break; Utils.debug.println(debugSpaces+"•Added implicit multiplications:"+processExpression);
case Simboli.POTENZA: }
f = new Potenza(null, null);
break; Utils.debug.println(debugSpaces+"•Subdivision in classes:");
case Simboli.PARENTHESIS_OPEN:
//cerca l'ultima parentesi chiusa debugSpaces += " ";
int startIndex = i;
int endIndex = -1;
int jumps = -1; //Suddividi tutto
for (int i2 = startIndex; i2 < processExpression.length(); i2++) { Parentesi parentesiNonSuddivisaCorrettamente = new Parentesi();
if ((processExpression.charAt(i2)+"").equals(Simboli.PARENTHESIS_CLOSE)) { parentesiNonSuddivisaCorrettamente.setVariables(new Funzione[]{});
if (jumps == 0) { String tmp = "";
endIndex = i2; Incognite tmpI = new Incognite();
break; final String[] funzioni = concat(concat(concat(concat(Simboli.funzioni(), Simboli.parentesi()), Simboli.segni(true)), Simboli.incognite()), Simboli.sintassiGenerale());
} else if (jumps > 0) { for (int i = 0; i < processExpression.length(); i++) {
jumps -= 1; //Per ogni carattere cerca se è un numero o una funzione:
} else if (jumps < 0) { String charI = processExpression.charAt(i)+"";
throw new Errore(Errori.UNBALANCED_BRACKETS); if (Utils.isInArray(charI, funzioni)) {
}
} else if ((processExpression.charAt(i2)+"").equals(Simboli.PARENTHESIS_OPEN)) { //Cerca il tipo di funzione tra le esistenti
jumps +=1; Funzione f = null;
} switch (charI) {
} case Simboli.SUM:
if (endIndex == -1 || endIndex < startIndex) { f = new Somma(null, null);
throw new Errore(Errori.UNBALANCED_BRACKETS); break;
} case Simboli.MULTIPLICATION:
startIndex += 1; f = new Moltiplicazione(null, null);
i = startIndex; break;
case Simboli.DIVISION:
String tmpExpr = ""; f = new Divisione(null, null);
while (i < endIndex) { break;
tmpExpr += processExpression.charAt(i); case Simboli.NTH_ROOT:
i++; f = new Radice(null, null);
} break;
f = new Parentesi(tmpExpr, debugSpaces); case Simboli.SQUARE_ROOT:
break; f = new RadiceQuadrata(null);
default: break;
throw new java.lang.RuntimeException("Il carattere "+charI+" non è tra le funzioni designate!\nAggiungerlo ad esse o rimuovere il carattere dall'espressione!"); case Simboli.POTENZA:
} f = new Potenza(null, null);
if (f instanceof Parentesi) { break;
tmp = ""; case Simboli.EQUATION:
} else { f = new Equazione(null, null);
if (tmp.length() != 0) { break;
parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Termine(tmp)); case Simboli.SYSTEM:
Utils.debug.println(debugSpaces+"•Added variable to expression:"+tmp); f = new ParteSistema(null);
} break;
} case Simboli.PARENTHESIS_OPEN:
parentesiNonSuddivisaCorrettamente.addVariableToEnd(f); //cerca l'ultima parentesi chiusa
Utils.debug.println(debugSpaces+"•Added variable to expression:"+f.simbolo()); int startIndex = i;
tmp = ""; int endIndex = -1;
} else { int jumps = -1;
try{ for (int i2 = startIndex; i2 < processExpression.length(); i2++) {
if (!(charI.equals("-") || charI.equals("."))) { if ((processExpression.charAt(i2)+"").equals(Simboli.PARENTHESIS_CLOSE)) {
Double.parseDouble(tmp + charI); if (jumps == 0) {
} endIndex = i2;
//Se il carattere è un numero intero, un segno negativo, o un punto break;
tmp += charI; } else if (jumps > 0) {
} catch (NumberFormatException exc) { jumps -= 1;
throw new java.lang.RuntimeException("Il carattere "+tmp+charI+" non è nè un numero nè un espressione presente nella lista completa!\nAggiungerlo ad essa o rimuovere il carattere dall'espressione!"); } else if (jumps < 0) {
} throw new Errore(Errori.UNBALANCED_BRACKETS);
} }
} } else if ((processExpression.charAt(i2)+"").equals(Simboli.PARENTHESIS_OPEN)) {
if (tmp.length() > 0) { jumps +=1;
Utils.debug.println(debugSpaces+"•Added variable to expression:"+tmp); }
parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Termine(tmp)); }
tmp = ""; if (endIndex == -1 || endIndex < startIndex) {
} throw new Errore(Errori.UNBALANCED_BRACKETS);
}
int dsl = debugSpaces.length();debugSpaces = "";for (int i = 0; i < dsl-2; i++) {debugSpaces += " ";} startIndex += 1;
Utils.debug.println(debugSpaces+"•Finished the subdivision in classes."); i = startIndex;
//Fine suddivisione di insieme String tmpExpr = "";
while (i < endIndex) {
//Inizia l'affinazione dell'espressione tmpExpr += processExpression.charAt(i);
Utils.debug.println(debugSpaces+"•Pushing classes..."); i++;
}
Funzione[] funzioniOLDArray = parentesiNonSuddivisaCorrettamente.getVariables(); f = new Parentesi(tmpExpr, debugSpaces, false);
ArrayList<Funzione> funzioniOLD = new ArrayList<Funzione>(); break;
for (int i = 0; i < funzioniOLDArray.length; i++) { default:
if (funzioniOLDArray[i] != null) { if (Utils.isInArray(charI, Simboli.incognite())) {
funzioniOLD.add(funzioniOLDArray[i]); //Fallback
} NumeroAvanzato na = NumeroAvanzato.ONE;
} Incognite iy = na.getIncognitey();
iy.incognite.add(new Incognita(charI.charAt(0), 1, 1));
Utils.debug.println(debugSpaces+"•Correcting classes:"); na = na.setIncognitey(iy);
f = new Termine(na);
debugSpaces += " "; } else {
throw new java.lang.RuntimeException("Il carattere "+charI+" non è tra le funzioni designate!\nAggiungerlo ad esse o rimuovere il carattere dall'espressione!");
int before = 0; }
String fase = "funzioniSN"; }
int n = 0; if (f instanceof Parentesi) {
do { tmp = "";
before = funzioniOLD.size(); } else if (f instanceof Termine) {
int i = 0; if (parentesiNonSuddivisaCorrettamente.getVariablesLength() == 0) {
boolean change = false; if (tmp.length() > 0) {
if (Utils.ciSonoSoloNumeriESomme(funzioniOLD)) { parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Termine(tmp));
fase = "somme"; //QUARTA FASE Utils.debug.println(debugSpaces+"•Added value to expression:"+tmp);
} else if (Utils.ciSonoFunzioniSNnonImpostate(funzioniOLD)) { parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Moltiplicazione(null, null));
fase = "funzioniSN"; // PRIMA FASE Utils.debug.println(debugSpaces+"•Added variable to expression:"+new Moltiplicazione(null, null).simbolo());
} else if (Utils.ciSonoAltreFunzioni(funzioniOLD)) { }
fase = "funzioniNSN"; //SECONDA FASE } else {
} else { if (tmp.length() > 0) {
fase = "moltiplicazioni"; //TERZA FASE if (parentesiNonSuddivisaCorrettamente.getVariable(parentesiNonSuddivisaCorrettamente.getVariablesLength()-1) instanceof Termine) {
} parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Moltiplicazione(null, null));
while (i < funzioniOLD.size() && change == false) { Utils.debug.println(debugSpaces+"•Added variable to expression:"+new Moltiplicazione(null, null).simbolo());
Funzione funzioneTMP = funzioniOLD.get(i); }
if (funzioneTMP instanceof FunzioneDueValori) { if (tmp.equals("-")) {
if (fase != "funzioniSN") { tmp = "-1";
if ( }
fase == "somme" && (funzioneTMP instanceof Somma) == true parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Termine(tmp));
|| Utils.debug.println(debugSpaces+"•Added value to expression:"+tmp);
(fase == "moltiplicazioni" && (funzioneTMP instanceof Somma) == false) }
|| if (tmp.length() > 0 || parentesiNonSuddivisaCorrettamente.getVariable(parentesiNonSuddivisaCorrettamente.getVariablesLength()-1) instanceof Termine) {
(fase == "funzioniNSN" && (funzioneTMP instanceof Somma) == false && (funzioneTMP instanceof Moltiplicazione) == false && (funzioneTMP instanceof Divisione) == false) parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Moltiplicazione(null, null));
) { Utils.debug.println(debugSpaces+"•Added variable to expression:"+new Moltiplicazione(null, null).simbolo());
change = true; }
if (i+1 < funzioniOLD.size() && i-1 >= 0 ) { }
((FunzioneDueValori) funzioneTMP).setVariable1(funzioniOLD.get(i-1)); } else {
((FunzioneDueValori) funzioneTMP).setVariable2(funzioniOLD.get(i+1)); if (tmp.length() != 0) {
funzioniOLD.set(i, funzioneTMP.calcola()); parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Termine(tmp));
Utils.debug.println(debugSpaces+"•Added variable to expression:"+tmp);
//è 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); parentesiNonSuddivisaCorrettamente.addVariableToEnd(f);
Utils.debug.println(debugSpaces+"•Added variable to expression:"+f.simbolo());
Utils.debug.println(debugSpaces+"•Set variable to expression:"+funzioneTMP.simbolo()); tmp = "";
Utils.debug.println(debugSpaces+" "+"var1="+((FunzioneDueValori) funzioneTMP).getVariable1().calcola()); } else {
Utils.debug.println(debugSpaces+" "+"var2="+((FunzioneDueValori) funzioneTMP).getVariable2().calcola()); try{
Utils.debug.println(debugSpaces+" "+"(result)="+((FunzioneDueValori) funzioneTMP).calcola()); if (charI.equals("-") == false && charI.equals(".") == false) {
} else { Double.parseDouble(tmp + charI);
throw new java.lang.RuntimeException("Argomenti mancanti! Sistemare l'equazione!"); }
} //Se il carattere è un numero intero, un segno negativo, o un punto
} tmp += charI;
} } catch (NumberFormatException exc) {
} else if (funzioneTMP instanceof FunzioneSingola) { throw new java.lang.RuntimeException("Il carattere "+tmp+charI+" non è nè un numero nè un espressione presente nella lista completa!\nAggiungerlo ad essa o rimuovere il carattere dall'espressione!");
if (fase == "funzioniSN") { }
change = true; }
if (i+1 < funzioniOLD.size()) { }
((FunzioneSingola) funzioneTMP).setVariable(funzioniOLD.get(i+1)); if (tmp.length() > 0) {
funzioniOLD.set(i, funzioneTMP); Utils.debug.println(debugSpaces+"•Added variable to expression:"+tmp);
parentesiNonSuddivisaCorrettamente.addVariableToEnd(new Termine(tmp));
//è importante togliere prima gli elementi in fondo e poi quelli davanti, perché gli indici scalano da destra a sinistra. tmp = "";
funzioniOLD.remove(i+1); }
Utils.debug.println(debugSpaces+"•Set variable to expression:"+funzioneTMP.simbolo()); int dsl = debugSpaces.length();debugSpaces = "";for (int i = 0; i < dsl-2; i++) {debugSpaces += " ";}
Utils.debug.println(debugSpaces+" "+"var="+((FunzioneSingola) funzioneTMP).getVariable().calcola()); Utils.debug.println(debugSpaces+"•Finished the subdivision in classes.");
} else { //Fine suddivisione di insieme
throw new java.lang.RuntimeException("Argomenti mancanti! Sistemare l'equazione!");
} Utils.debug.println(debugSpaces+"•Removing useless parentheses");
} for (int i = 0; i < parentesiNonSuddivisaCorrettamente.variables.length; i++) {
} else if (funzioneTMP instanceof Termine || funzioneTMP instanceof Parentesi) { if (parentesiNonSuddivisaCorrettamente.variables[i] instanceof Parentesi) {
if (n < 300) { Parentesi par = (Parentesi) parentesiNonSuddivisaCorrettamente.variables[i];
//Utils.debug.println(debugSpaces+"•Set variable to number:"+funzioneTMP.calcola()); if (par.variables.length == 1) {
} Funzione subFunz = par.variables[0];
} else { if (subFunz instanceof Parentesi || subFunz instanceof Termine) {
throw new java.lang.RuntimeException("Tipo sconosciuto"); parentesiNonSuddivisaCorrettamente.variables[i] = subFunz;
} Utils.debug.println(debugSpaces+" •Useless parentheses removed");
i++; }
n++; }
} }
} while (funzioniOLD.size() != before || fase != "somme"); }
setVariables(funzioniOLD);
//Inizia l'affinazione dell'espressione
dsl = debugSpaces.length();debugSpaces = "";for (int i = 0; i < dsl-2; i++) {debugSpaces += " ";} Utils.debug.println(debugSpaces+"•Pushing classes...");
Utils.debug.println(debugSpaces+"•Finished correcting classes.");
Funzione[] funzioniOLDArray = parentesiNonSuddivisaCorrettamente.getVariables();
Utils.debug.println(debugSpaces+"•Result:"+calcola()); ArrayList<Funzione> funzioniOLD = new ArrayList<Funzione>();
} for (int i = 0; i < funzioniOLDArray.length; i++) {
} if (funzioniOLDArray[i] != null) {
funzioniOLD.add(funzioniOLDArray[i]);
@Override }
public String simbolo() { }
return "Parentesi";
} Utils.debug.println(debugSpaces+" •Correcting classes:");
@Override int before = 0;
public Termine calcola() throws Errore { String fase = "funzioniSN";
Termine result = new Termine(BigSurdVec.ZERO); int n = 0;
for (Funzione f : variables) { do {
result = result.add(f.calcola()); before = funzioniOLD.size();
} int i = 0;
return result; boolean change = false;
} if (Utils.ciSonoFunzioniSNnonImpostate(funzioniOLD)) {
fase = "funzioniSN"; // PRIMA FASE
} } else if (Utils.ciSonoFunzioniNSNnonImpostate(funzioniOLD)) {
fase = "funzioniNSN"; //SECONDA FASE
} else if (Utils.ciSonoMoltiplicazioniNonImpostate(funzioniOLD)) {
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 && funzioniOLD.size() > 1) {
Funzione funzioneTMP = funzioniOLD.get(i);
if (funzioneTMP instanceof FunzioneDueValori) {
if (fase != "funzioniSN") {
if (
(
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)
&&
(
(
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 == "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;
if (i+1 < funzioniOLD.size() && i-1 >= 0 ) {
((FunzioneDueValori) funzioneTMP).setVariable1(funzioniOLD.get(i-1));
((FunzioneDueValori) funzioneTMP).setVariable2(funzioniOLD.get(i+1));
funzioniOLD.set(i, funzioneTMP);
//è 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());
try {Utils.debug.println(debugSpaces+" "+"var1="+((FunzioneDueValori) funzioneTMP).getVariable1().calcola());} catch (NullPointerException ex2) {}
try {Utils.debug.println(debugSpaces+" "+"var2="+((FunzioneDueValori) funzioneTMP).getVariable2().calcola());} catch (NullPointerException ex2) {}
try {Utils.debug.println(debugSpaces+" "+"(result)="+((FunzioneDueValori) funzioneTMP).calcola());} catch (NullPointerException ex2) {}
} else {
throw new java.lang.RuntimeException("Argomenti mancanti! Sistemare l'equazione!");
}
}
}
} else if (funzioneTMP instanceof FunzioneAnteriore) {
if (
(
fase == "funzioniSN"
&&
((FunzioneAnteriore) funzioneTMP).variable == null
)
||
(
fase == "sistemi"
&&
funzioneTMP instanceof ParteSistema
)
) {
change = true;
if (i+1 < funzioniOLD.size()) {
((FunzioneAnteriore) funzioneTMP).setVariable(funzioniOLD.get(i+1));
funzioniOLD.set(i, funzioneTMP);
//è importante togliere prima gli elementi in fondo e poi quelli davanti, perché gli indici scalano da destra a sinistra.
funzioniOLD.remove(i+1);
Utils.debug.println(debugSpaces+" •Set variable to expression:"+funzioneTMP.simbolo());
Utils.debug.println(debugSpaces+" "+"var="+((FunzioneAnteriore) funzioneTMP).getVariable().calcola().toString());
} else {
throw new java.lang.RuntimeException("Argomenti mancanti! Sistemare l'equazione!");
}
}
} else if (funzioneTMP instanceof Termine || funzioneTMP instanceof Parentesi) {
if (n < 300) {
//Utils.debug.println(debugSpaces+" •Set variable to number:"+funzioneTMP.calcola());
}
} else {
throw new java.lang.RuntimeException("Tipo sconosciuto");
}
i++;
n++;
}
} while (((funzioniOLD.size() != before || fase != "sistemi") && funzioniOLD.size() > 1));
setVariables(funzioniOLD);
dsl = debugSpaces.length();debugSpaces = "";for (int i = 0; i < dsl-2; i++) {debugSpaces += " ";}
Utils.debug.println(debugSpaces+"•Finished correcting classes.");
Termine result = calcola();
Utils.debug.println(debugSpaces+"•Result:"+result);
}
}
@Override
public String simbolo() {
return "Parentesi";
}
public ParteSistema calcolaSistema() throws Errore {
return new ParteSistema(calcolaEquazione());
}
public Equazione calcolaEquazione() throws Errore {
return new Equazione(calcola(), new Termine("0"));
}
@Override
public Termine calcola() throws Errore {
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) {
result = result.add(f.calcola());
}
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,18 +1,46 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
public class Potenza extends FunzioneDueValori { import org.warp.engine.Display;
public Potenza(Funzione value1, Funzione value2) { public class Potenza extends FunzioneDueValori {
super(value1, value2);
} public Potenza(Funzione value1, Funzione value2) {
super(value1, value2);
@Override }
public String simbolo() {
return Simboli.POTENZA; @Override
} public String simbolo() {
return Simboli.POTENZA;
@Override }
public Termine calcola() throws NumberFormatException, Errore {
return getVariable1().calcola().pow(getVariable2().calcola()); @Override
} public Termine calcola() throws NumberFormatException, Errore {
} 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,22 +1,41 @@
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 {
public Radice(Funzione value1, Funzione value2) {
super(value1, value2); public Radice(Funzione value1, Funzione value2) {
} super(value1, value2);
}
@Override
public String simbolo() { @Override
return Simboli.NTH_ROOT; public String simbolo() {
} return Simboli.NTH_ROOT;
}
@Override
public Termine calcola() throws NumberFormatException, Errore { @Override
Termine exponent = new Termine(BigSurdVec.ONE); public Termine calcola() throws NumberFormatException, Errore {
exponent = exponent.divide(getVariable1().calcola()); Termine exponent = new Termine(NumeroAvanzatoVec.ONE);
return getVariable2().calcola().pow(exponent); exponent = exponent.divide(getVariable1().calcola());
} 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,20 +1,46 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import org.nevec.rjm.Rational; import org.nevec.rjm.NumeroAvanzatoVec;
import org.nevec.rjm.Rational;
public class RadiceQuadrata extends FunzioneSingola { import org.warp.engine.Display;
public RadiceQuadrata(Funzione value) { public class RadiceQuadrata extends FunzioneAnteriore {
super(value);
} public RadiceQuadrata(Funzione value) {
super(value);
@Override }
public String simbolo() {
return Simboli.SQUARE_ROOT; @Override
} public String simbolo() {
return Simboli.SQUARE_ROOT;
@Override }
public Termine calcola() throws NumberFormatException, Errore {
return getVariable().calcola().pow(new Termine(Rational.ONE.divide(new Rational(2,1)))); @Override
} public Termine calcola() throws NumberFormatException, Errore {
} 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

@ -1,34 +1,43 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import static org.warpgate.pi.calculator.Utils.concat; 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 MULTIPLICATION = "*"; public static final String SUBTRACTION = "-";
public static final String DIVISION = "/"; public static final String MULTIPLICATION = "*";
public static final String NTH_ROOT = ""; public static final String DIVISION = "/";
public static final String SQUARE_ROOT = ""; public static final String NTH_ROOT = "";
public static final String PARENTHESIS_OPEN = "("; public static final String SQUARE_ROOT = "";
public static final String PARENTHESIS_CLOSE = ")"; public static final String PARENTHESIS_OPEN = "(";
public static final String POTENZA = "^"; public static final String PARENTHESIS_CLOSE = ")";
public static final String POTENZA = "";
public static final String[] funzioni() { public static final String EQUATION = "=";
return concat(funzioniNSN(), funzioniSN()); public static final String SYSTEM = "{";
}
public static final String[] funzioniNSN() { public static final String[] funzioni() {
return new String[]{NTH_ROOT, POTENZA}; return concat(funzioniNSN(), funzioniSN());
} }
public static final String[] funzioniSN() { public static final String[] funzioniNSN() {
return new String[]{SQUARE_ROOT}; return new String[]{NTH_ROOT, POTENZA};
} }
public static final String[] segni(boolean withMultiplication) { public static final String[] funzioniSN() {
String[] ret = new String[]{SUM, DIVISION}; return new String[]{SQUARE_ROOT};
if (withMultiplication) { }
ret = Utils.add(ret, MULTIPLICATION); public static final String[] segni(boolean withMultiplication) {
} String[] ret = new String[]{SUM, DIVISION};
return ret; if (withMultiplication) {
} ret = Utils.add(ret, MULTIPLICATION);
public static final String[] parentesi() { }
return new String[]{PARENTHESIS_OPEN, PARENTHESIS_CLOSE}; return ret;
} }
} public static final String[] parentesi() {
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,19 +1,61 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
public class Somma extends FunzioneDueValori { import java.awt.Color;
import java.math.BigInteger;
public Somma(Funzione value1, Funzione value2) {
super(value1, value2); import org.nevec.rjm.NumeroAvanzatoVec;
} import org.warp.engine.Display;
@Override public class Somma extends FunzioneDueValori {
public String simbolo() {
return Simboli.SUM; public Somma(Funzione value1, Funzione value2) {
} super(value1, value2);
}
@Override
public Termine calcola() throws Errore { @Override
return getVariable1().calcola().add(getVariable2().calcola()); public String simbolo() {
} return Simboli.SUM;
}
}
@Override
public Termine calcola() throws Errore {
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,143 +1,378 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import java.math.BigDecimal; import java.awt.Color;
import java.math.BigInteger; import java.awt.Graphics;
import java.math.MathContext; import java.math.BigDecimal;
import java.util.ArrayList; import java.math.BigInteger;
import java.math.MathContext;
import org.nevec.rjm.BigDecimalMath; import java.util.ArrayList;
import org.nevec.rjm.BigSurd;
import org.nevec.rjm.BigSurdVec; import org.nevec.rjm.BigDecimalMath;
import org.nevec.rjm.Rational; import org.nevec.rjm.NumeroAvanzato;
import org.nevec.rjm.NumeroAvanzatoVec;
public class Termine implements Funzione { import org.nevec.rjm.Rational;
import org.warp.engine.Display;
protected BigSurdVec term = BigSurdVec.ZERO;
protected ArrayList<VariabileEdEsponente> variables = new ArrayList<VariabileEdEsponente>(); import com.rits.cloning.Cloner;
public Termine(BigSurdVec val) { public class Termine implements Funzione {
term = val;
} protected NumeroAvanzatoVec term = NumeroAvanzatoVec.ZERO;
public Termine(String s) { public Termine(NumeroAvanzatoVec val) {
term = new BigSurdVec(new BigSurd(Utils.getRational(s), Rational.ONE)); term = val;
} }
public Termine(Rational r) { public Termine(String s) {
term = new BigSurdVec(new BigSurd(r, Rational.ONE)); term = new NumeroAvanzatoVec(new NumeroAvanzato(Utils.getRational(s), Rational.ONE));
} }
public Termine(BigInteger r) { public Termine(Rational r) {
term = new BigSurdVec(new BigSurd(new Rational(r, BigInteger.ONE), Rational.ONE)); term = new NumeroAvanzatoVec(new NumeroAvanzato(r, Rational.ONE));
} }
public Termine(BigDecimal r) { public Termine(BigInteger r) {
term = new BigSurdVec(new BigSurd(Utils.getRational(r), Rational.ONE)); term = new NumeroAvanzatoVec(new NumeroAvanzato(new Rational(r, BigInteger.ONE), Rational.ONE));
} }
public BigSurdVec getTerm() { public Termine(BigDecimal r) {
return term; term = new NumeroAvanzatoVec(new NumeroAvanzato(Utils.getRational(r), Rational.ONE));
} }
public void setTerm(BigSurdVec val) { public Termine(NumeroAvanzato numeroAvanzato) {
term = val; term = new NumeroAvanzatoVec(numeroAvanzato);
} }
public ArrayList<VariabileEdEsponente> getVariables() { public NumeroAvanzatoVec getTerm() {
return variables; return term;
} }
public void setVariables(ArrayList<VariabileEdEsponente> variables) { public void setTerm(NumeroAvanzatoVec val) {
this.variables = variables; term = val;
} }
@Override @Override
public Termine calcola() { public Termine calcola() {
return this; return this;
} }
@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()); return ret;
if (f.getVariables().size() > 0) { }
System.err.println("Moltiplicazioni con variabili non implementato");
throw new Errore(Errori.NOT_IMPLEMENTED); public Termine multiply(Termine f) throws Errore {
} Termine ret = new Termine(getTerm().multiply(f.getTerm()));
return ret; return ret;
} }
public Termine multiply(Termine f) throws Errore { public Termine divide(Termine f) throws Errore {
Termine ret = new Termine(getTerm().multiply(f.getTerm())); Termine ret = new Termine(getTerm().divide(f.getTerm()));
ret.setVariables(getVariables()); return ret;
if (f.getVariables().size() > 0) { }
System.err.println("Moltiplicazioni con variabili non implementato");
throw new Errore(Errori.NOT_IMPLEMENTED); public Termine pow(Termine f) throws Errore {
} Termine ret = new Termine(NumeroAvanzatoVec.ONE);
return ret; if (f.getTerm().isBigInteger(true)) {
} for (BigInteger i = BigInteger.ZERO; i.compareTo(f.getTerm().toBigInteger(true)) < 0; i = i.add(BigInteger.ONE)) {
ret = ret.multiply(new Termine(getTerm()));
public Termine divide(Termine f) throws Errore { }
Termine ret = new Termine(getTerm().divide(f.getTerm())); } else if (getTerm().isRational(true) && f.getTerm().isRational(false) && f.getTerm().toRational(false).compareTo(Rational.HALF) == 0) {
ret.setVariables(getVariables()); //Rational originalExponent = f.getTerm().toRational();
if (f.getVariables().size() > 0) { //Rational rootExponent = new Rational(originalExponent.denom(), originalExponent.numer());
System.err.println("Divisioni con variabili non implementato"); Rational numberToRoot = getTerm().toRational(true);
throw new Errore(Errori.NOT_IMPLEMENTED); NumeroAvanzato na = new NumeroAvanzato(Rational.ONE, numberToRoot);
} na = na.setIncognitex(getTerm().toNumeroAvanzato().getIncognitey().multiply(getTerm().toNumeroAvanzato().getIncognitez()));
return ret; na = na.setIncognitey(new Incognite());
} na = na.setIncognitez(getTerm().toNumeroAvanzato().getIncognitez());
ret = new Termine(na);
public Termine pow(Termine f) throws Errore { } else {
Termine ret = new Termine(BigSurdVec.ONE); ret = new Termine(BigDecimalMath.pow(getTerm().BigDecimalValue(new MathContext(Utils.scale, Utils.scaleMode2)), f.getTerm().BigDecimalValue(new MathContext(Utils.scale, Utils.scaleMode2))));
if (f.getTerm().isBigInteger()) { }
for (BigInteger i = BigInteger.ZERO; i.compareTo(f.getTerm().toBigInteger()) < 0; i = i.add(BigInteger.ONE)) { return ret;
ret = ret.multiply(new Termine(getTerm())); }
ret.setVariables(getVariables());
if (f.getVariables().size() > 0) { @Override
System.err.println("Potenze con variabili non implementato"); public String toString() {
throw new Errore(Errori.NOT_IMPLEMENTED); return getTerm().toFancyString();
} }
}
} else if (getTerm().isRational() && f.getTerm().isRational() && f.getTerm().toRational().denom().compareTo(BigInteger.ONE) == 0) { public void draw(int x, int y, Display g, boolean small, boolean drawMinus) {
ret = new Termine(getTerm().toRational().pow(f.getTerm().toRational())); boolean beforedrawminus = this.drawMinus;
ret.setVariables(getVariables()); this.drawMinus = drawMinus;
if (f.getVariables().size() > 0) { draw(x, y, g, small);
System.err.println("Potenze con variabili non implementato"); this.drawMinus = beforedrawminus;
throw new Errore(Errori.NOT_IMPLEMENTED); }
}
} else if (getTerm().isRational() && f.getTerm().isRational() && f.getTerm().toRational().compareTo(Rational.HALF) == 0) { private boolean drawMinus = true;
//Rational originalExponent = f.getTerm().toRational();
//Rational rootExponent = new Rational(originalExponent.denom(), originalExponent.numer()); @Override
Rational numberToRoot = getTerm().toRational(); public void draw(int x, int y, Display g, boolean small) {
ret = new Termine(new BigSurdVec(new BigSurd(Rational.ONE, numberToRoot))); if (getTerm().isBigInteger(false)) {
ret.setVariables(getVariables()); String t = toString();
if (f.getVariables().size() > 0) { int w1 = Utils.getPlainTextWidth(t);
System.err.println("Potenze con variabili non implementato"); int h1 = Utils.getFontHeight(small);
throw new Errore(Errori.NOT_IMPLEMENTED);
} if (t.startsWith("-")) {
} else { if (drawMinus) {
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()); } else {
if (f.getVariables().size() > 0) { int minusw = Utils.getPlainTextWidth("-");
System.err.println("Potenze con variabili non implementato"); int minush = Utils.getFontHeight(small);
throw new Errore(Errori.NOT_IMPLEMENTED); t = t.substring(1);
} }
} }
return ret; Utils.writeLetter(g, t, x, y, small);
} } else if (getTerm().isRational(false)) {
small = true;
@Override Rational r = getTerm().toRational(false);
public String toString() { boolean minus = false;
if (getTerm().isBigInteger()) { int minusw = 0;
return getTerm().toBigInteger().toString(); int minush = 0;
} else if (getTerm().isRational()) { String numerator = r.numer().toString();
return getTerm().toRational().toString(); if (numerator.startsWith("-")) {
} else { minus = true;
return getTerm().toFancyString(); 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,156 +1,366 @@
package org.warpgate.pi.calculator; package org.warpgate.pi.calculator;
import java.io.StringWriter; import java.awt.Color;
import java.math.BigDecimal; import java.awt.FontMetrics;
import java.math.BigInteger; import java.awt.Graphics;
import java.math.RoundingMode; import java.awt.image.BufferedImage;
import java.util.ArrayList; import java.io.StringWriter;
import java.math.BigDecimal;
import org.nevec.rjm.BigDecimalMath; import java.math.BigInteger;
import org.nevec.rjm.Rational; import java.math.MathContext;
import java.math.RoundingMode;
public class Utils { import java.util.ArrayList;
public static final int scale = 130; import org.nevec.rjm.BigDecimalMath;
import org.nevec.rjm.Rational;
public static final int scaleMode = BigDecimal.ROUND_HALF_UP; import org.warp.engine.Display;
public static final RoundingMode scaleMode2 = RoundingMode.HALF_UP; import org.warp.engine.Display.Font;
public static DebugStream debug = new DebugStream(); public class Utils {
public static boolean debugOn; public static final int scale = 130;
public static final int resultScale = 8;
public static final class DebugStream extends StringWriter {
public static final int scaleMode = BigDecimal.ROUND_HALF_UP;
public void println(String str) { public static final RoundingMode scaleMode2 = RoundingMode.HALF_UP;
if (debugOn) { public static final Font fontBig = new Font("CalcBig", Font.PLAIN, 16);
System.err.println(str); public static final Font fontSmall = new Font("CalcSmall", Font.PLAIN, 16);
}
} public static DebugStream debug = new DebugStream();
int before = 0;
boolean due = false; public static boolean debugOn;
} public static final class DebugStream extends StringWriter {
public static boolean isInArray(String ch, String[] a) { public void println(String str) {
boolean contains = false; if (debugOn) {
for (String c : a) { System.err.println(str);
if (c.equals(ch)) { }
contains = true; }
break; int before = 0;
} boolean due = false;
}
return contains; }
}
public static String ArrayToRegex(String[] array) { public static boolean isInArray(String ch, String[] a) {
String regex = null; boolean contains = false;
for(String symbol : array) { for (String c : a) {
if (regex != null) { if (c.equals(ch)) {
regex+="|\\"+symbol; contains = true;
} else { break;
regex = "\\"+symbol; }
} }
} return contains;
return regex; }
} public static String ArrayToRegex(String[] array) {
public static String[] concat(String[] a, String[] b) { String regex = null;
int aLen = a.length; for(String symbol : array) {
int bLen = b.length; if (regex != null) {
String[] c= new String[aLen+bLen]; regex+="|\\"+symbol;
System.arraycopy(a, 0, c, 0, aLen); } else {
System.arraycopy(b, 0, c, aLen, bLen); regex = "\\"+symbol;
return c; }
} }
public static String[] add(String[] a, String b) { return regex;
int aLen = a.length; }
String[] c= new String[aLen+1]; public static String[] concat(String[] a, String[] b) {
System.arraycopy(a, 0, c, 0, aLen); int aLen = a.length;
c[aLen] = b; int bLen = b.length;
return c; String[] c= new String[aLen+bLen];
} System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
public static boolean ciSonoSoloNumeriESomme(ArrayList<Funzione> fl) { return c;
for (int i = 0; i < fl.size(); i++) { }
if (!(fl.get(i) instanceof Termine || fl.get(i) instanceof Somma || fl.get(i) instanceof Parentesi)) { public static String[] add(String[] a, String b) {
return false; int aLen = a.length;
} String[] c= new String[aLen+1];
} System.arraycopy(a, 0, c, 0, aLen);
return true; c[aLen] = b;
} return c;
}
public static boolean ciSonoFunzioniSNnonImpostate(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) { public static boolean ciSonoSoloFunzioniImpostateSommeEquazioniESistemi(ArrayList<Funzione> fl) {
if (fl.get(i) instanceof FunzioneSingola) { for (int i = 0; i < fl.size(); i++) {
if (((FunzioneSingola)fl.get(i)).variable == null) { 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)) {
return true; 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;
public static boolean ciSonoAltreFunzioni(ArrayList<Funzione> fl) { }
for (int i = 0; i < fl.size(); i++) { } else {
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)) { return false;
return true; }
} }
} }
return false; return true;
} }
public static boolean ciSonoSoloFunzioniImpostateSommeMoltiplicazioniEquazioniESistemi(ArrayList<Funzione> fl) {
public static Rational getRational(BigDecimal str) { for (int i = 0; i < fl.size(); i++) {
return getRational(str.toString()); 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) {
public static Rational getRational(String str) { return false;
try { }
return new Rational(str); } else if (fl.get(i) instanceof FunzioneDueValori) {
} catch (NumberFormatException ex) { if (((FunzioneDueValori)fl.get(i)).variable1 == null || ((FunzioneDueValori)fl.get(i)).variable2 == null) {
long bits = Double.doubleToLongBits(Double.parseDouble(str)); return false;
}
long sign = bits >>> 63; } else {
long exponent = ((bits >>> 52) ^ (sign << 11)) - 1023; return false;
long fraction = bits << 12; // bits are "reversed" but that's not a problem }
}
long a = 1L; }
long b = 1L; return true;
}
for (int i = 63; i >= 12; i--) {
a = a * 2 + ((fraction >>> i) & 1); public static boolean ciSonoSoloFunzioniImpostateEquazioniESistemi(ArrayList<Funzione> fl) {
b *= 2; 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 (exponent > 0) if (((FunzioneAnteriore)fl.get(i)).variable == null) {
a *= 1 << exponent; return false;
else }
b *= 1 << -exponent; } else if (fl.get(i) instanceof FunzioneDueValori) {
if (((FunzioneDueValori)fl.get(i)).variable1 == null || ((FunzioneDueValori)fl.get(i)).variable2 == null) {
if (sign == 1) return false;
a *= -1; }
} else {
if (b == 0) { return false;
a = 0; }
b = 1; }
} }
return true;
}
return new Rational(new BigInteger(a+""),new BigInteger(b+""));
} 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)) {
public static BigDecimal rationalToIrrationalString(Rational r) { if (fl.get(i) instanceof FunzioneAnteriore) {
return BigDecimalMath.divideRound(new BigDecimal(r.numer()).setScale(Utils.scale, Utils.scaleMode), new BigDecimal(r.denom()).setScale(Utils.scale, Utils.scaleMode)); if (((FunzioneAnteriore)fl.get(i)).variable == null) {
} return false;
public static boolean variabiliUguali(ArrayList<VariabileEdEsponente> variables, ArrayList<VariabileEdEsponente> variables2) { }
if (variables.size() != variables2.size()) { } else if (fl.get(i) instanceof FunzioneDueValori) {
return false; if (((FunzioneDueValori)fl.get(i)).variable1 == null || ((FunzioneDueValori)fl.get(i)).variable2 == null) {
} else { return false;
for (VariabileEdEsponente v : variables) { }
if (!variables2.contains(v)) { } else {
return false; return false;
} }
} }
return true; }
} return true;
} }
}
public static boolean ciSonoFunzioniSNnonImpostate(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) {
if (fl.get(i) instanceof FunzioneAnteriore && !(fl.get(i) instanceof ParteSistema)) {
if (((FunzioneAnteriore)fl.get(i)).variable == null) {
return true;
}
}
}
return false;
}
public static boolean ciSonoFunzioniNSNnonImpostate(ArrayList<Funzione> fl) {
for (int i = 0; i < fl.size(); i++) {
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 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;
}
public static Rational getRational(BigDecimal str) {
return getRational(str.toString());
}
public static Rational getRational(String str) {
try {
return new Rational(str);
} 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 sign = bits >>> 63;
long exponent = ((bits >>> 52) ^ (sign << 11)) - 1023;
long fraction = bits << 12; // bits are "reversed" but that's not a problem
long a = 1L;
long b = 1L;
for (int i = 63; i >= 12; i--) {
a = a * 2 + ((fraction >>> i) & 1);
b *= 2;
}
if (exponent > 0)
a *= 1 << exponent;
else
b *= 1 << -exponent;
if (sign == 1)
a *= -1;
if (b == 0) {
a = 0;
b = 1;
}
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) {
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<Incognita> variables, ArrayList<Incognita> variables2) {
if (variables.size() != variables2.size()) {
return false;
} else {
for (Incognita v : variables) {
if (!variables2.contains(v)) {
return false;
}
}
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;
}
}