Uma biblioteca robusta em Dart para programação matemática abrangente. Oferece expressões, números complexos, álgebra, estatística, ângulos e geometria para cálculos diversos.
Orientação gerada a partir de informações públicas. Apenas para referência.
Uma biblioteca Dart abrangente projetada para cálculos matemáticos avançados. Suporta expressões, números complexos, operações algébricas, análise estatística, cálculos de ângulos e funções geométricas. Ideal para aplicações que exigem manipulação matemática precisa em múltiplos domínios. A biblioteca é independente de plataforma, funcionando sem problemas no Android, iOS, macOS, Windows e Linux. Criada para desenvolvedores que precisam de ferramentas matemáticas robustas sem dependências externas.
Casos de uso
Computação científica
Aplicativos educacionais
simulações de engenharia
Análise de dados
jogos baseados em geometria
Principais recursos
Suporta números complexos
Avaliação de expressão algébrica
Funções estatísticas
Utilitários de ângulo e geometria
Compatibilidade multiplataforma
Indicado para
aplicações intensivas em matemática
Ferramentas de educação STEM
Desenvolvimento de software técnico
Implementação de algoritmo
Protótipos de pesquisa
Considerações
Requer conhecimento de conceitos matemáticos
Pode ter curva de aprendizado para iniciantes
Não otimizado para desempenho em tempo real
Documentação limitada em algumas áreas
Depende de um ambiente Dart estável
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
Advance Math Library for Dart
Advance math is a comprehensive Dart library that enriches mathematical programming in Dart with a wide range of features beyond vectors and matrices. Offering functionality for complex numbers, advanced linear algebra, statistics, geometry, and more. The library opens up new possibilities for mathematical computation and data analysis. Whether you're developing a cutting-edge machine learning application, or simply need to perform calculations with complex numbers. It also provides the tools you need in a well-organized and easy-to-use package.
Features
Basic statistics: Statistics operations like mean, median, mode, min, max, variance, standardDeviation, quartiles,permutations, combinations, greatest common divisor(gcd), least common multiple(lcm).
Convert number types to words. It also supports to currency formats for cheques and ordinal words representations.
Morse code translations for encoding and decoding.
Logarithmic operations: natural logarithm of a number, base-10 logarithm and logarithm of a number to a given base.
Support angle conversion (degrees, minutes, seconds, radians, gradians, DMS).
Trigonometry: It provides computation on all the trigonometric functions on the angle. These includes inverse and hyperbolic function (sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, sec, csc, cot, asec, acsc, acot, sech, csch, coth, asech, acsch, acoth, vers, covers, havers, exsec, excsc).
Angle operation: Supports addition, subtraction, multiplication, and division. Also supports comparisons, normalize, interpolation, and small-differencing on angles.
Geometry: Geometries like Point, Line, Polygon, Circle, Triangle, SphericalTriangle, etc with specific functionalities and methods are implemented.
Polynomial functions: Solve and find roots of a function to any degree (including Linear, Quadratic, Cubic, Quartic etc).
Roman numerals: Convert roman numerals to integers and vice versa. It also supports basic arithmetic operations and comparisons.
Matrix creation, filling and generation: Methods for filling the matrix with specific values or generating matrices with certain properties, such as zero, ones, identity, diagonal, list, or random matrices.
Import and export matrices to and from other formats (e.g., CSV, JSON, binary)
Matrix operations: Implement common matrix operations such as addition, subtraction, multiplication (element-wise and matrix-matrix), and division (element-wise) etc.
Matrix transformation methods: Add methods for matrix transformations, such as transpose, inverse, pseudoInverse, and rank etc.
Statistical methods: Methods for calculating statistical properties of the matrix, such as min, max, sum, mean, median, mode, skewness, standard deviation, and variance.
Element-wise operations: Methods for performing element-wise operations on the matrix, such as applying a function to each element or filtering elements based on a condition.
Solving linear systems of equations (Using Inverse Matrix, LU Decomposition,Gauss-Jordan Elimination, Ridge Regression, Gauss Elimination, Least Squares, Jacobi, Successive Over-Relaxation (SOR), Gauss-Seidel method, Gram Schmidt, Conjugate Gradient, Montante's Method (Bareiss algorithm) and Cramers Rule)
Solve matrix decompositions like LU decomposition, QR decomposition, LQ decomposition, Cholesky, Singular Value Decomposition (SVD) with different algorithms Crout's, Doolittle, Gauss Elimination Method, Gram Schmidt, Householder, Partial and Complete Pivoting, etc.
Matrix slicing and partitioning: Methods for extracting sub-Matrices or slices from the matrix.
Matrix concatenation and stacking: Methods for concatenating or stacking matrices horizontally or vertically.
Matrix norms: Methods for calculating matrix norms, such as L1 (Marathan), L2 (Euclidean), and infinity norms.
Determine the properties of a matrix.
From the matrix, row and columns of the matrix are iterables and also iterate on every element.
Eigen values and vectors.
Supports vectors, complex numbers and complex vectors with most of the basic functionalities and operations.
Supports math expressions with context and functions.
Enhanced expression creation with multiple approaches: explicit Literal objects, toExpression() extension method, and ex() helper function.
Symbolic Calculus & Integral Transforms: Support for partial derivatives, indefinite and definite integration, Taylor and Maclaurin series expansions, limits, and summations symbolically.
Laplace & Inverse Laplace Transforms: Compute symbolic Laplace transforms and their inverse transforms.
Equation Solving & Systems of Equations: Solve single linear, quadratic, and cubic equations, as well as multi-equation systems symbolically and numerically.
Usage
Import the library
import'package:advance_math/advance_math.dart';
LOGARITHM
Logarithm
Base-10 logarithm of a number is also implemented.
print(log10(100)); // Output: 2.0
Compute the natural logarithm of of a number using the function below. It also supports computes logarithm to any base.
// Natural log of `e`print(log(math.e)); // Output: 1.0//log to any base. Example log to base 10 on 100print(log(100, 10)); // prints: 2.0
Compute the logarithm of a number to a given base.
This library provides a class, MorseCode, for encoding and decoding messages using the Morse code system. It offers custom delimiters for characters, words, and new lines in Morse code. The class also includes a rate limiter to prevent abuse of the encode/decode functions and optional logging for debugging purposes.
main(){
// Create an instance of morse code translatorvar translator = MorseCode();
// Convert words to morse codevar encoded = translator.encode('SOS');
print('Encoded: $encoded'); // Encoded: ... --- ...print('');
// Convert the morse code to wordsvar decoded = translator.decode(encoded);
print('Decoded: $decoded'); // Decoded: SOS
}
Rate Limiting and Logging
The MorseCodeTranslator class includes a rate limiter to prevent abuse of the encode/decode functions. You can enable or disable logging by setting the loggingEnabled flag to true or false. When logging is enabled, informational messages will be logged to the console.
Caching
To improve efficiency, the translator caches previously decoded Morse code strings. This allows for faster decoding of repeated messages without having to recompute them.
NumOrWords (Numbers or Words) is a Dart class designed to convert numerical values into their word representations and vice-versa. It is highly customizable, catering to multiple languages, currency representations, and more.
Features
Basic Number Conversion: Convert any number into its word representation.
Currency Representation: Represent numbers in their currency form (e.g., Dollars, Euros).
Decimal Precision: Define the precision for decimal numbers.
Ordinal Numbers: Convert numbers into their ordinal form (e.g., 1st, 2nd, 3rd).
Multiple Languages Support: Easily extendable for multiple languages.
Number Extension: Conveniently use the Dart extension on numbers for quick conversion.
Basic Usage
To begin, instantiate the NumOrWords class by providing language configurations.
var converter = NumOrWords(languages: {'en': englishConfig});
Converting a Number to Words
Simply call the convert method on the converter instance.
print(converter.toWords(45.6743)); // Forty-Five Point Six Seven Four Three
Defining Decimal Precision
You can also specify the precision for decimal numbers.
print(converter.toWords(45.6743, decimalPlaces: 10)); // Forty-Five Point Six Seven Four Three
Currency Representation
To represent numbers in their currency form, specify the currency.
print(converter.convert(45.6743, currency: usd)); // Forty-Five Dollars And Sixty-Seven Cents Only
Using the Number Extension
For convenience, the package also provides an extension on the number type.
print(45.67.toWords(currency: usd)); // Forty-Five Dollars And Sixty-Seven Cents Only
Advanced Number Conversions
The package can handle a variety of number forms and scenarios.
print(converter.toWords(0)); // Zeroprint(converter.toWords(1)); // Oneprint(converter.toWords(10)); // Tenprint(converter.toWords(100)); // One Hundredprint(converter.toWords(101)); // One Hundred And Oneprint(converter.toWords(111)); // One Hundred And Eleven
Ordinal Numbers
To convert numbers into their ordinal form, use the useOrdinal parameter.
The supports only French and English for the mean time. You can convert number to either English or French and back to number with losing precision.
voiddisplayConversion(NumOrWords converter, num value,
{String lang = 'en',
int decimalPlaces = 2,
bool useOrdinal = false,
bool isFeminine = false,
Currency? currency}) {
var result = converter.toWords(value,
lang: lang,
decimalPlaces: decimalPlaces,
useOrdinal: useOrdinal,
isFeminine: isFeminine,
currency: currency);
print(result);
print(converter.toNum(result, lang: lang, currency: currency));
print('---');
}
var converter = NumOrWords();
print('--- French ---');
displayConversion(converter, 301, lang: 'fr', useOrdinal: true);
displayConversion(converter, 123, lang: 'fr', decimalPlaces: 10);
displayConversion(converter, 6743, lang: 'fr', decimalPlaces: 10);
displayConversion(converter, 123.6743, lang: 'fr', decimalPlaces: 10);
displayConversion(converter, 123.6743, lang: 'fr', currency: cefaCurrency);
displayConversion(converter, 84656789, lang: 'fr');
displayConversion(converter, 9181601, lang: 'fr');
displayConversion(converter, 8666529123484656789, lang: 'fr');
print('\n--- English ---');
displayConversion(converter, 301, lang: 'en', useOrdinal: true);
displayConversion(converter, 123, lang: 'en', decimalPlaces: 10);
displayConversion(converter, 6743, lang: 'en', decimalPlaces: 10);
displayConversion(converter, 123.6743, lang: 'en', decimalPlaces: 10);
displayConversion(converter, 123.6743, lang: 'en', currency: usdCurrency);
displayConversion(converter, 9181601, lang: 'en');
displayConversion(converter, 8666529123484656789, lang: 'en');
// --- French ---// Trois Cents-et-Un// 301// ---// Cent et Vingt-et-Trois// 123// ---// Six Mille Sept Cents et Quarante-et-Trois// 6743// ---// Cent et Vingt-et-Trois Point Six Mille Sept Cents et Quarante-et-Trois// 123.6743// ---// Cent et Vingt-et-Trois Francs et Soixante-et-Sept Centimes Seulement// 123.67// ---// Quatre-Vingt-et-Quatre Million Six Cents et Cinquante-et-Six Mille Sept Cents et Quatre-Vingt-et-Neuf// 84656789// ---// Neuf Million Cent et Quatre-Vingt-et-Un Mille Six Cents et Un// 9181601// ---// Huit Trillion Six Cents et Soixante-et-Six Billiard Cinq Cents et Vingt-et-Neuf Billion Cent et Vingt-et-Trois Milliard Quatre Cents et Quatre-Vingt-et-Quatre Million Six Cents et Cinquante-et-Six Mille Sept Cents et Quatre-Vingt-et-Neuf// 8666529123484656789// ---//// --- English ---// Three Hundred And First// 301// ---// One Hundred And Twenty-Three// 123// ---// Six Thousand Seven Hundred And Forty-Three// 6743// ---// One Hundred And Twenty-Three Point Six Thousand Seven Hundred And Forty-Three// 123.6743// ---// One Hundred And Twenty-Three Dollars And Sixty-Seven Cents Only// 123.67// ---// Nine Million One Hundred And Eighty-One Thousand Six Hundred And One// 9181601// ---// Eight Quintillion Six Hundred And Sixty-Six Quadrillion Five Hundred And Twenty-Nine Trillion One Hundred And Twenty-Three Billion Four Hundred And Eighty-Four Million Six Hundred And Fifty-Six Thousand Seven Hundred And Eighty-Nine// 8666529123484656789// ---
LanguageConfig and Currency Configurations
The LanguageConfig and Currency classes are central to the NumOrWords package. They allow for deep customization and extensibility to cater to different languages and currency formats.
Currency Configuration
For currency representation, you can define the singular and plural forms of both main and fractional units using the Currency class.
These configurations (Currency and LanguageConfig) form the backbone of the NumOrWords package. By leveraging their flexibility, users can accurately convert numbers to word representations for a vast range of languages and currency formats. Whether you're targeting a single language or a global audience, NumOrWords ensures precision and extensibility.
In the above example, the Currency configuration is set for US Dollars, with "Dollar" as the singular form, "Dollars" as the plural, "Cent" as the fractional singular, and "Cents" as the fractional plural.
LanguageConfig
The LanguageConfig class provides a comprehensive configuration for number-word conversion in a specific language. It defines the word representations for different number sections, such as ones, tens, hundreds, magnitudes, etc., and also handles special conditions like ordinals.
Example:
/// An English configuration for conversionfinalLanguageConfig englishConfig = LanguageConfig(
ones: {
'0': "Zero",
'1': "One",
'2': "Two",
'3': "Three",
'4': "Four",
'5': "Five",
'6': "Six",
'7': "Seven",
'8': "Eight",
'9': "Nine"
},
teens: {
'10': "Ten",
'11': "Eleven",
'12': "Twelve",
'13': "Thirteen",
'14': "Fourteen",
'15': "Fifteen",
'16': "Sixteen",
'17': "Seventeen",
'18': "Eighteen",
'19': "Nineteen"
},
tens: {
'2': "Twenty",
'3': "Thirty",
'4': "Forty",
'5': "Fifty",
'6': "Sixty",
'7': "Seventy",
'8': "Eighty",
'9': "Ninety"
},
hundreds: {
'1': "One Hundred",
'2': "Two Hundred",
'3': "Three Hundred",
'4': "Four Hundred",
'5': "Five Hundred",
'6': "Six Hundred",
'7': "Seven Hundred",
'8': "Eight Hundred",
'9': "Nine Hundred"
},
magnitudes: [
"",
"Thousand",
"Million",
"Billion",
"Trillion",
"Quadrillion",
"Quintillion",
"Sextillion",
"Septillion",
"Octillion",
"Nonillion",
"Decillion",
"Undecillion",
"Duodecillion",
"Tredecillion",
"Quattuordecillion",
"Quindecillion",
"Sexdecillion",
"Septendecillion",
"Octodecillion",
"Novemdecillion",
"Vigintillion"
],
fractionalSeparator: 'Point',
negativeTerm: 'Negative',
currencySuffix: 'Only',
tensDelimiter: "-",
ordinalSuffixes: {1: "st", 2: "nd", 3: "rd", -1: "th"},
ordinalFunction: (value, {bool isFeminine = false}) {
// Helper function to get the ordinal for numbers from 1 to 19StringsimpleOrdinal(intnum) {
if (num == 1) return'First';
if (num == 2) return'Second';
if (num == 3) return'Third';
if (num == 4) return'Fourth';
if (num == 5) return'Fifth';
if (num == 6) return'Sixth';
if (num == 7) return'Seventh';
if (num == 8) return'Eighth';
if (num == 9) return'Ninth';
if (num == 12) return'Twelfth';
return"${englishConfig.convertChunk(num)}${englishConfig.ordinalSuffixes[-1]!}";
}
StringtwoDigitOrdinal(intnum) {
if (num >= 10 && num < 20) {
// Special cases for 11th to 19threturn englishConfig.teens["$num"]! +
englishConfig.ordinalSuffixes[-1]!;
}
if (num >= 20) {
int tensPart = num ~/ 10;
int onesPart = num % 10;
var v = englishConfig.tens["$tensPart"]!;
if (onesPart == 0) {
return"${v.substring(0, v.length - 1)}ieth";
} else {
return"$v-${simpleOrdinal(onesPart)}";
}
}
returnsimpleOrdinal(num);
}
if (value < 100) {
returntwoDigitOrdinal(value);
}
String cardinal = englishConfig.convertChunk(value);
List<String> parts = cardinal.split(' ');
// For numbers above 99, replace only the last part with its ordinalString lastPartOrdinal = twoDigitOrdinal(value % 100);
parts[parts.length - 1] = lastPartOrdinal;
return parts.join(' ');
},
reverseOrdinalFunction: (value) {
value = value.replaceFirst('First', 'One');
value = value.replaceFirst('Second', 'Two');
value = value.replaceFirst('Third', 'Three');
value = value.replaceFirst('Fourth', 'Four');
value = value.replaceFirst('Fifth', 'Five');
value = value.replaceFirst('Sixth', 'Six');
value = value.replaceFirst('Seventh', 'Seven');
value = value.replaceFirst('Eighth', 'Eight');
value = value.replaceFirst('Ninth', 'Nine');
value = value.replaceFirst('Twelfth', 'Twelve');
// Split the input into wordsList<String> words = value.split(RegExp(r'[\s\-]'));
if (words.last.endsWith('ieth')) {
value = value.replaceFirst(
words.last, '${words.last.substring(0, words.last.length - 4)}y');
} elseif (words.last.endsWith('th')) {
value = value.replaceFirst(
words.last, words.last.substring(0, words.last.length - 2));
}
return value;
},
chunkConversionRule: (num currentValue, String word, LanguageConfig config) {
if (word == "Hundred") {
return currentValue == 0 ? 100 : currentValue * 100;
} elseif (config.magnitudes.contains(word)) {
num magnitudeValue = pow(10, config.magnitudes.indexOf(word) * 3);
return currentValue * magnitudeValue;
}
return0; // Default case, can be adjusted as needed
},
defaultConjunction: "And",
unitsBeforeTens: false,
);
In the provided example, the LanguageConfig is set for English. It specifies the words for ones, tens, hundreds, etc., and also handles the logic for ordinals. The configuration also includes details like the word for negative numbers (Negative), currency suffix (Only), and the delimiter used between tens and ones (-).
Extending for Multiple Languages
To support multiple languages, simply extend the LanguageConfig for each language and provide it to the NumOrWords class.
Conclusion
NumOrWords offers a comprehensive solution for converting numbers into words, supporting a wide range of use-cases and customization. Whether you need simple word representation or complex multi-language support with currency, NumOrWords has got you covered.
ZScore
ZScore
Computes Z-scores based on a given confidence level.
The class provides functionalities to compute Z-scores, which are used in statistical hypothesis testing.
The Z-score represents how many standard deviations an element is from the mean.
var confidenceLevels = [
10,
20,
30,
40,
50,
60,
70,
80,
85,
90,
95,
99.0,
99.999,
99.99999,
99.9999999
];
for (var cl in confidenceLevels) {
double zScore = ZScore.computeZScore(cl);
print("Z-score for $cl% confidence level is $zScore");
}
// Z-score for 10% confidence level is 0.12538099310291884// Z-score for 20% confidence level is 0.25293326782658254// Z-score for 30% confidence level is 0.3848770849965131// Z-score for 40% confidence level is 0.5240018703826799// Z-score for 50% confidence level is 0.6741891400433162// Z-score for 60% confidence level is 0.8414567173547839// Z-score for 70% confidence level is 1.0364314851895606// Z-score for 80% confidence level is 1.281728756502709// Z-score for 85% confidence level is 1.4398004696260025// Z-score for 90% confidence level is 1.645211440143815// Z-score for 95% confidence level is 1.9603949169253396// Z-score for 99.0% confidence level is 2.5762360813095704// Z-score for 99.999% confidence level is 4.417087697546128// Z-score for 99.99999% confidence level is 5.326446072058037// Z-score for 99.9999999% confidence level is 6.109029815669355
Compute the confidence level using the Z-Scroe value
Confidence interval around a sample mean, you generally need the sample mean (x), the sample size (n), and the standard deviation (σ) or the standard error of the sample mean (SE). The Z-score corresponding to the desired confidence level is also required.
// Compute p-value from a given Z-score.print(ZScore.computePValue(1.96)); // 0.025// Convert Z-score to T-score.print(ZScore.convertZToT(1.96)); // 69.6// Compute the percentile from a given Z-score.print(ZScore.computePercentile(1.96)); // 97.5// Compute Z-score from a raw score.print(ZScore.computeZScoreFromRawScore(110, 100, 15)); // 0.6666666666666666
ANGLE
Angle Class
The Angle class is part of the advanced_math library. It's designed to make working with angles straightforward in a variety of units, including degrees, radians, gradians, and DMS (Degrees, Minutes, Seconds).
Features
Create an Angle object with any of the four units. The class will automatically convert it to all other units and store them as properties:
var angleDeg = Angle.degrees(45);
var angleRad = Angle.radians(math.pi / 4);
var angleGrad = Angle.gradians(50);
var angleDMS = Angle.dms([45, 0, 0]);
Perform all the possible trignometry functions on the angle:
var angle = Angle.degrees(45);
var t1 = angle.sin();
var t2 = angle.cos();
var t3 = angle.tan();
var t4 = angle.tanh();
var t5 = angle.atanh();
These features provide an easy-to-use interface for handling various angle calculations, especially for applications that require geometric computations or work with geospatial data. The Angle class is an essential part of the advanced_math library and can be useful for anyone who needs advanced mathematical operations in Dart.
GEOMETRY
Geometry Library
This library provides a suite of classes and functions to work with geometric objects and perform geometric calculations.
A SphericalTriangle is a triangle on the surface of a sphere. It can be created by providing the lengths of its sides and the radius of the sphere.
var triangle = SphericalTriangle.fromAllSides( Angle(rad: pi / 2), Angle(rad: pi / 3), Angle(rad: pi / 4));
// Anglesprint('AngleA: ${triangle.angleA} '); // AngleA: Angle: 35.26438968275524° or 0.6154797086703871 rad or [35, 15, 51.802857918852396]print('AngleB: ${triangle.angleB} '); // AngleB: Angle: 125.26438968275677° or 2.186276035465284 rad or [125, 15, 51.80285792437758]print('AngleC: ${triangle.angleC}'); // AngleC: Angle: 45.00000000000074° or 0.785398163397448 rad or [45, 0, 2.660272002685815e-9]// Sidesprint('SideA: ${triangle.sideA}'); // SideA: Angle: 90.00000000000152° or 1.5707963267948966 rad or [90, 0, 5.474021236295812e-9]print('SideB: ${triangle.sideB}'); // SideB: Angle: 60.00000000000101° or 1.0471975511965976 rad or [60, 0, 3.632294465205632e-9]print('SideC: ${triangle.sideC} '); // SideC: Angle: 45.00000000000076° or 0.7853981633974483 rad or [45, 0, 2.737010618147906e-9]print('Area: ${triangle.area} ≈ ${triangle.areaPercentage} % of unit sphere surface area'); // Area: 0.445561253943326 ≈ 3.545663800765179 % of unit sphere surface areaprint('Perimeter: ${triangle.perimeter} ≈ ${triangle.perimeterPercentage} % of unit sphere circumference'); // Perimeter: 3.4033920413889422 ≈ 54.166666666666664 % of unit sphere circumferenceprint('isValidTriangle: ${triangle.isValidTriangle()}'); // isValidTriangle: true
AnnulusSector
An AnnulusSector represents a ring-like sector bounded by two concentric circular arcs of different radii and two radial boundaries.
The Geometry Library provides comprehensive support for Polynomials. This includes polynomials of different degrees, from linear to quartic, as well as a general polynomial implementation using the Durand-Kerner method for degrees of 5 or higher.
Usage
Linear
Linear polynomials are of the form ax + b = 0.
Linear linear = Linear.num(a: 2, b: -3);
print(linear.roots()); // Output: [1.5]
Quadratic
Quadratic polynomials are of the form ax² + bx + c = 0.
A Dart class designed to provide efficient conversions between Roman numerals and integers. This class also supports arithmetic operations directly on Roman numeral representations.
Features
Convert integers to Roman numerals and vice versa.
Supports numbers up to 3,999 using standard Roman numerals.
Supports numbers above 3,999 using parentheses notation.
var v = Matrix([
[1, 2, 3],
[4, 5, 6],
[1, 3, 5]
]);
var b = Matrix([
[7, 8, 9],
[4, 6, 8],
[1, 2, 3]
]);
var r = RowMatrix([7, 8, 9]);
var c = ColumnMatrix([7, 4, 1]);
var d = DiagonalMatrix([1, 2, 3]);
print(d);
// Output:// 1 0 0// 0 2 0// 0 0 3
Change or use element value
v[1][2] = 0;
var u = v[1][2] + r[0][1];
print(u); // 9var z = v[0][0] + c[0][0];
print(z); // 8var y = v[1][2] + b[1][1];
print(y); // 9var k = v.row(1); // Get all elements in row 1print(k); // [1,2,3]var n = v.column(1); // Get all elements in column 1print(n); // [1,4,1]
Index (row,column) of an element in the matrix
var mat = Matrix.fromList([
[2, 3, 3, 3],
[9, 9, 8, 6],
[1, 1, 2, 9]
]);
var index = mat.indexOf(8);
print(index);
// Output: [1, 2]var indices = mat.indexOf(3, findAll: true);
print(indices);
// Output: [[0, 1], [0, 2], [0, 3]]
var matrix = Matrix([[1, 2], [3, 4]]);
var reshaped = matrix.reshape(1, 4);
print(reshaped);
// Output:// 1 2 3 4
Solving Linear Systems of Equations
Use the solve method to solve a linear system of equations:
Matrix a = Matrix([[2, 1, 1], [1, 3, 2], [1, 0, 0]]);;
Matrix b = Matrix([[4], [5], [6]]);
// Solve the linear system Ax = bMatrix x = a.linear.solve(b, method: LinearSystemMethod.gaussElimination);
print(x.round(1));
// Output:// Matrix: 3x1// ┌ 6.0 ┐// │ 15.0 │// └ -23.0 ┘
You can also use the the decompositions to solve a linear system of equations
Matrix A = Matrix([
[4, 1, -1],
[1, 4, -1],
[-1, -1, 4]
]);
Matrix b = Matrix([
[6],
[25],
[14]
]);
//Solve using the Schur DecompositionSchurDecomposition schur = A.decomposition.schurDecomposition();
//Solve using the QR Decomposition HouseholderQRDecomposition qr = A.decomposition.qrDecompositionHouseholder();
// Solve for x using the objectvar x = qr.solve(b).round();
print(x);
// Output:// Matrix: 3x1// ┌ 1 ┐// │ 7 │// └ 6 ┘
Boolean Operations
Some functions in the library that results in boolean values
Roll elements along a given axis. Elements that roll beyond the last position are re-introduced at the first.
This function work exactly like the NumPy's roll.
shift : int or tuple of ints
The number of places by which elements are shifted. If a tuple, then axis must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If an int while axis is a tuple of ints, then the same value is used for all given axes.
axis : int or tuple of ints or null
Axis or axes along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored.
The Matrix class provides various other functions for matrix manipulation and analysis.
// Swap rowsvar matrix = Matrix([[1, 2], [3, 4]]);
matrix.swapRows(0, 1);
print(matrix);
// Output:// Matrix: 2x2// ┌ 3 4 ┐// └ 1 2 ┘// Swap columns
matrix.swapColumns(0, 1);
print(matrix);
// Output:// Matrix: 2x2// ┌ 4 3 ┐// └ 2 1 ┘// Get the leading diagonal of the matrixvar m = Matrix([[1, 2], [3, 4]]);
var diag = m.diagonal();
print(diag);
// Output: [1, 4]// Iterate through elements in the matrix using map functionvar doubled = m.map((x) => x * 2);
print(doubled);
// Output:// Matrix: 2x2// ┌ 2 4 ┐// └ 6 8 ┘
VECTOR
Create a new vector
Vector(int length, {bool isDouble = true}): Creates a [Vector] of given length with all elements initialized to 0.
Vector.fromList(List<num> data): Constructs a [Vector] from a list of numerical values.
Vector.random(int length,{double min = 0, double max = 1, bool isDouble = true, math.Random? random, int? seed}): Constructs a [Vector] from a list of random numerical values.
Vector.linspace(int start, int end, [int number = 50]): Creates a row Vector with equally spaced values between the start and end values (inclusive).
Vector.range(int end, {int start = 1, int step = 1}) & Vector.arrange(int end, {int start = 1, int step = 1}): Creates a Vector with values in the specified range, incremented by the specified step size.
// Create a vector of length 3 with all elements initialized to 0var v1 = Vector(3);
// Create a vector from a list of valuesvar v2 = Vector([1, 2, 3]);
v2 = Vector.fromList([1, 2, 3]);
// Create a vector with random values between 0 and 1var v3 = Vector.random(3);
// Create a vector with 50 values equally spaced between 0 and 1var v4 = Vector.linspace(0, 1);
// Create a vector with values 1, 3, 5, 7, 9var v5 = Vector.range(10, start: 1, step: 2);
v5 = Vector.arrange(10, start: 1, step: 2);
Operators
Supports operations for element-wise operations by scalar value or vector
// Get the value at index 2 of v2var val = v2[2];
// Set the value at index 1 of v1 to 7
v1[1] = 7;
// Add v1 and v2var v6 = v1 + v2;
// Subtract v2 from v1var v7 = v1 - v2;
// Multiply v1 by a scalarvar v8 = v1 * 3.5;
// Divide v2 by a scalarvar v9 = v2 / 2;
Vector Operations
double dot(Vector other): Calculates the dot product of the vector with another vector.
Vector cross(Vector other): Calculates the cross product of the vector with another vector.
double get magnitude: Returns the magnitude (or norm) of the vector.
double get direction: Returns the direction (or angle) of the vector, in radians.
double norm(): Returns the norm (or length) of this vector.
Vector normalize(): Returns this vector normalized.
bool isZero(): Returns true if this is a zero vector, i.e., all its elements are zero.
bool isUnit(): Returns true if this is a unit vector, i.e., its norm is 1.
// Calculate the dot product of v1 and v2var dotProduct = v1.dot(v2);
// Calculate the cross product of two 3D vectorsvar crossProduct = Vector.fromList([1, 2, 3]).cross(Vector.fromList([4, 5, 6]));
// Get the magnitude of v1var magnitude = v1.magnitude;
// Get the direction of v1var direction = v1.direction;
// Get the norm of v1var norm = v1.norm();
// Normalize v1var normalizedV1 = v1.normalize();
Others metrics include:
List<num> toList(): Converts the vector to a list of numerical values.
int get length: Returns the length (number of elements) of the vector.
void setAll(num value): Sets all elements of this vector to [value].
double distance(Vector other): Returns the Euclidean distance between this vector and [other].
Vector projection(Vector other): Returns the projection of this vector onto [other].
double angle(Vector other): Returns the angle (in radians) between this vector and [other].
List<double> toSpherical(): Converts the Vector from Cartesian to Spherical coordinates.
void fromSpherical(List<num> sphericalCoordinates): Converts the Vector from Spherical to Cartesian coordinates.
Vector v = Vector([1, 2, 3]);
print(v); // Output: [1, 2, 3]// Convert v1 to a listvar list = v1.toList();
// Get the length of v1var length = v1.length;
// Set all elements of v1 to 5
v1.setAll(5);
// Calculate the Euclidean distance between v1 and v2var distance = v1.distance(v2);
// Calculate the projection of v1 onto v2var projection = v1.projection(v2);
// Calculate the angle between v1 and v2var angle = v1.angle(v2);
// Convert v1 to spherical coordinatesvar spherical = v1.toSpherical();
// Create a vector from spherical coordinatesvar v10 = Vector(3);
v10.fromSpherical(spherical);
It's possible to use vector instances as keys for HashMap and similar data structures and to look up a value by the vector-key, since the hash code for equal vectors is the same.
This library provides efficient and easy-to-use classes for representing and manipulating vectors, complex numbers, and complex vectors in Dart. This document serves as an introduction to these classes, featuring a variety of examples to demonstrate their usage.
Complex Numbers
Complex numbers extend the concept of the one-dimensional number line to the two-dimensional complex plane by using the number i, where i^2 = -1.
Complex numbers are crucial in many areas of mathematics and engineering.
The Complex class in this library lets you create complex numbers, access their real and imaginary parts, and obtain their conjugate.
Constructors
The class provides several constructors to create complex numbers in different ways:
var z1 = Complex(1, 2); // Creates a complex number 1 + 2ivar z2 = Complex.fromPolar(2, pi / 2); // Creates a complex number from polar coordinatesvar z3 = Complex.fromReal(1); // Creates a complex number with only a real partvar z4 = Complex.fromImaginary(2); // Creates a complex number with only an imaginary partvar z5 = Complex.parse('2 + 2i'); // Parses a complex number from a string
Access its properties
// Creating a new complex numberComplex z = Complex(3, 2);
print(z); // Output: 3 + 2i// Accessing the real and imaginary partsprint(z.real); // Output: 3print(z.imaginary); // Output: 2// ConjugationComplex conjugate = z.conjugate();
print(conjugate); // Output: 3 - 2i
Operations
The class supports all basic arithmetic operations, including addition, subtraction, multiplication, division, and exponentiation:
var z1 = Complex(1, 2);
var z2 = Complex(2, 3);
var sum = z1 + z2; // Adds two complex numbersvar difference = z1 - z2; // Subtracts two complex numbersvar product = z1 * z2; // Multiplies two complex numbersvar quotient = z1 / z2; // Divides two complex numbersvar mod = z1 % 2; // Modulo operation of complex numbersvar power = z1 ^ 2; // Raises a complex number to a power
Power Operator
The power operator (^) raises the complex number to the power of the given number. The result is another complex number.
var z = Complex(2, 3); // 2 + 3ivar z_power = z ^ 2;
print(z_power); // Output: -5 + 12i
In this example, the complex number z is raised to the power of 2. The result is another complex number -5 + 12i.
var z = Complex(1, 2); // 1 + 2ivar z_power = z ^ Complex(2, 1); // (2 + i)print(z_power); // Output: -1.6401010184280038 + 0.202050398556709i
In this example, the complex number z is raised to the power of another complex number 2 + i. The result is another complex number -1.6401010184280038 + 0.202050398556709i.
Other methods
The class also provides several other methods to work with complex numbers
var z = Complex(1, 2);
var magnitude = z.magnitude; // Gets the magnitude (or absolute value) of the complex numbervar angle = z.angle; // Gets the angle (or argument or phase) in radians of the complex numbervar conjugate = z.conjugate; // Gets the conjugate of the complex numbervar real = z.real; // Gets the real part of the complex numbervar imaginary = z.imaginary; // Gets the imaginary part of the complex numbervar sqrt = z.sqrt(); // Gets the square root of the complex numbervar exp = z.exp(); // Gets the exponential of the complex numbervar ln = z.ln(); // Gets the natural logarithm (base e) of the complex numbervar sin = z.sin(); // Gets the sine of the complex numbervar cos = z.cos(); // Gets the cosine of the complex numbervar tan = z.tan(); // Gets the tangent of the complex number
Complex vectors
ComplexVectors are a type of vector where the elements are complex numbers. They are especially important in quantum mechanics and signal processing.
The ComplexVector class provides ways to create complex vectors, perform operations on them such as addition, and calculate their norm and normalized form.
The above sections provide a basic introduction to vectors, complex numbers, and complex vectors. The full API of these classes offers even more possibilities, including conversions to other forms of vectors, multiplication by scalars, and more. These classes aim to make mathematical programming in Dart efficient, flexible, and enjoyable.
EXPRESSIONS
This module demonstrates the usage of mathematical expressions in Dart. It includes examples of handling positional and named arguments, evaluating various mathematical expressions, and performing operations on polynomials and multi-variable polynomials.
Features in expression library
Enhanced Expression Creation: Three intuitive approaches for creating expressions with numeric literals
Explicit Literal objects (traditional approach)
Extension method toExpression() for fluent APIs
Helper function ex() for concise syntax
Examples
Positional and Named Arguments
Average Function
Evaluating Expressions
Simple Math
Complex Math
Conditional Math
Logic Math
String Math
DateTime Math
Polynomials
Multi-variable Polynomials
Expression Math
Extension Methods
Examples
Positional and Named Arguments
This example demonstrates handling positional and named arguments using the VarArgsFunction.
dynamic superHeroes = VarArgsFunction((args, kwargs) {
for (final superHero in args) {
print("There's no stopping $superHero");
}
});
superHeroes('UberMan', 'Exceptional Woman', 'The Hunk'); // Positional args onlydynamic myFunc = VarArgsFunction((args, kwargs) {
print('Got args: $args, kwargs: $kwargs');
});
myFunc(1, 2, 3, x: 'hello', y: 'world'); // Positional + Named argsmyFunc(10, 20, x: true, y: false); // Another set of Positional + Named argsmyFunc('A', 'B', 'C'); // Positional args only
Average Function
This example demonstrates using the avg function to calculate the average of numbers.
print(avg([1, 2, 3, 4, 5])); // This will print the average of the numbersprint(avg(1, 2, 3, 4, 5));
Helper Functions and Constants
These are helper function to support the examples:
// Create custom contextfinal context1 = {
'x': 3.0,
'y': 4.0,
'z': 2,
'a': true,
'b': [1, 2, 3],
'pi': pi,
'e': e,
};
// Merge it with the default contextfinal context = {...defaultContext, ...context1};
var parsec = ExpressionParser();
voidprintExpressionResult(String expression, dynamic context) {
try {
var result = parsec.parse(expression).evaluate(context);
print('Expression: $expression => $result');
} catch (e) {
print('Error evaluating expression `$expression`: $e');
}
}
voidevaluateExpressions(
List<String> expressions, String category, dynamic context) {
printLine(category);
for (var expr in expressions) {
printExpressionResult(expr, context);
}
}
Evaluating Expressions
This example demonstrates evaluating a list of expressions.
This section showcases a rich set of capabilities available in the CAS parser and expression evaluator, spanning complex numbers, polynomials, statistics, and algebraic transformations:
1. Complex Numbers in Expressions
Evaluate complex number arithmetic, power functions, roots, and trigonometric/hyperbolic operations:
Generate Taylor or Maclaurin series expansions of expressions around a center:
final x = Variable('x');
// Taylor series of x^2 around x=1, up to order 2:final taylor = SymbolicCalculus.taylorSeries(x ^ ex(2), 'x', 1, 2);
print('Taylor of x^2: $taylor'); // 1 + 2*(x - 1) + (x - 1)^2// Maclaurin series of cos(x) up to order 4:final maclaurin = SymbolicCalculus.maclaurinSeries(Cos(x), 'x', 4);
print('Maclaurin of cos(x): $maclaurin'); // 1 - x^2/2 + x^4/24
Equation Solver & Systems of Equations
Solve single equations (linear, quadratic, cubic) or systems of equations symbolically or numerically:
final x = Variable('x');
final y = Variable('y');
// 1. Solving a single equation (e.g. x^2 - 9 = 0)final eq1 = Subtract(Pow(x, ex(2)), ex(9));
final solutions = ExpressionSolver.solve(eq1, x);
print('Solutions: $solutions'); // [3, -3]// 2. Solving systems of linear equations (e.g. x + y = 5, x - y = 1)final equations = [
Expression.parse('x + y - 5'),
Expression.parse('x - y - 1'),
];
final sysSolutions = ExpressionSolver.solveEquations(equations, [x, y]);
print('System Solutions: $sysSolutions'); // [3.0, 2.0]
All three methods produce equivalent results and can be mixed within the same expression. Choose the approach that best fits your coding style:
Use ex() for simple expressions: ex(2) * x + ex(3)
Use toExpression() for fluent APIs: 2.toExpression() * x + 3.toExpression()
Use Literal() for explicit control: Literal(2) * x + Literal(3)
Mix approaches for complex expressions: 2.toExpression() * x + ex(3) * y - Literal(1)
For comprehensive examples and troubleshooting, see:
example/enhanced_expression_creation.dart
doc/enhanced_expression_creation.md
doc/expression_troubleshooting.md
doc/expression_migration_guide.md
Extension Methods
This project includes extension methods for the num type to allow for operator overloading with expressions.
These extension methods allow for more intuitive and readable code when working with expressions.
SYMBOLIC CALCULUS & COMPUTER ALGEBRA SYSTEM (CAS)
Symbolic Calculus & CAS
The advance_math library features a complete symbolic calculus package (lib/src/math/algebra/calculus) built on top of the Expression parser. This allows developers to construct, simplify, differentiate, integrate, and transform mathematical expressions programmatically.
1. Symbolic Differentiation
Compute derivatives and partial derivatives of expressions with respect to specific variables:
import'package:advance_math/advance_math.dart';
var x = Variable('x');
// Differentiate x^2 + 2xvar expr = (x ^ ex(2)) + ex(2) * x;
var deriv = expr.differentiate();
print('Derivative: $deriv'); // 2*x + 2// Partial derivatives: ∂/∂x (x^3)var poly = Expression.parse('x^3');
var partial = SymbolicCalculus.partialDerivative(poly, 'x');
print('Partial: $partial'); // 3*x^2 (Evaluated at x=2 yields 12.0)
2. Symbolic Integration (Indefinite & Definite)
Perform indefinite and definite integration over algebraic and trigonometric functions:
Expand complex expressions into Taylor or Maclaurin series approximations up to arbitrary orders:
// Taylor series of sin(x) around x=0 up to order 5var sinExpr = Sin(Variable('x'));
var taylor = SymbolicCalculus.taylorSeries(sinExpr, 'x', 0, 5);
print('Taylor (sin): $taylor'); // x - x^3/6 + x^5/120// Maclaurin series of exp(x) up to order 4var expExpr = Exp(Variable('x'));
var maclaurin = SymbolicCalculus.maclaurinSeries(expExpr, 'x', 4);
print('Maclaurin (exp): $maclaurin'); // 1 + x + x^2/2 + x^3/6 + x^4/24
4. Limits and Summations
Evaluate limits (including indeterminate forms using L'Hopital's rule) and summations:
To prevent redundant computations during heavy calculus operations (like numerical derivatives or adaptive integration), the library uses an LRU (Least Recently Used) cache:
// Numerical differentiation with high-order caching// computes 7th derivative of e^x efficientlyvar numDeriv = NumericalDifferentiation.nthDerivative((x) => exp(x), 0, 7);
print('7th derivative of e^x at x=0: $numDeriv'); // 1.0
PERFORMANCE CACHING, MEMOIZATION & UTILITIES
Performance Caching & Memoization
To ensure maximum performance for expensive calculus operations, the library integrates a powerful caching and memoization framework (lib/src/utils/memoize.dart).
Caching in Calculus (Differentiation & Integration)
Repeatedly differentiating or integrating the same mathematical expressions benefits from local caching, avoiding redundant symbolic computation.
import'package:advance_math/advance_math.dart';
var x = Variable('x');
var expr = (x ^ ex(3)) + ex(2) * (x ^ ex(2)) - ex(5) * x;
// Differentiation is computed and the symbolic result is cached internallyvar firstDeriv = expr.differentiate();
// Subsequent calls retrieve the computed derivative from cache instantaneouslyvar cachedDeriv = expr.differentiate();
Collection Extensions
The library extends standard Dart collections with optimized mathematical helper methods to simplify numerical data pipelines.
Cumulative Sum (cumsum())
Calculates the cumulative sum of numerical values in an iterable.