FEATURES AND SYNTAX
- Units can be append to expressions to produce convertions (see below).
- You can omit the multiplier sign between brackets, function, constants, like in real world (see examples)
- Support unlimited levels of brackets.
- Expression can contain spaces and tabs.
- Functions, and units (see below) SHOULD be lowercase.
- Constants (see below) ARE case sensitive, but you can use the greek notation if available.
- Support scientific notation like: 1.2345e-6 (lowercase "e")
- Support hexadecimal (OxABCD) and unsigned binary (²010101) numbers. Note that hexadecimal numbers could be lowercase (0xfedc) but the prefix (0x) should NOT be uppercase.
Notes:
If expression contain at least one hexadecimal number, the result will be expressed in hexadecimal form (with the leading "0x").
If expression contain at least one binary number, the result will be expressed in binary form (with the leading "²"), unless it also contain a hexadecimal number.
To force the result into an arbitrary base, prefix the expression with a lowercase "b" (binary), "h" (hexadecimal) or "d" (decimal), like this: "b 0xFF+1"
Readme:
Code:
EXPRESSION OPERATORS (IN DESCENDING PRECEDENCE ORDER)
**, ^
Power. Both the base and the exponent may contain a decimal point.
Since ** is of higher precedence than unary minus, -2**2 is evaluated like -(2**2) and so yields -4. Thus, to raise a literal negative number to a power, enclose it in parentheses such as (-2)**2.
Note: A negative base combined with a fractional exponent such as (-2)**0.5 is not supported; it will yield an empty string. But both (-2)**2 and (-2)**2.0 are supported.
!
Factorial of a positive integer.
Since ! is of higher precedence than unary minus, -3! is evaluated like -(3!) and so yields -6.
*, /
Multiply (*) and true divide (/).
//, \
Floor divide. Result is truncated to the nearest integer to the left.
For example, 5//3.0 equals 1 and 5.0//-3 equals -2.
+, -
Add (+) and subtract (-).
mod
Modulo (Dividend mod Divisor): Returns the remainder when Dividend is divided by Divisor. The sign of the result is always the same as the sign of the first parameter. For example, both (5 mod 3) and (5 mod -3) yield 2, but (-5 mod 3) and (-5 mod -3) yield -2.
If either input is a floating point number, the result is also a floating point number. For example, (5 mod 3.5) is 1.5.
<<, >>
Bit shift left (<<) and right (>>). Usage: Value1 << Value2. Any floating point input is truncated to an integer prior to the calculation. Shift left (<<) is equivalent to multiplying Value1 by "2 to the Value2th power". Shift right (>>) is equivalent to dividing Value1 by "2 to the Value2th power" and rounding the result to the nearest integer leftward on the number line; for example, -3>>1 is -2
and, or, xor
Bitwise-and (and), bitwise-exclusive-or (xor), and bitwise-or (or). Of the three, "and" has the highest precedence and "or" has the lowest. Any floating point input is truncated to an integer prior to the calculation.
MATHEMATICAL FUNCTIONS
sqrt(n): Square root of n.
log(n): Logarithm (base 10) of n. If n is negative, an empty string is returned.
ln(n): Natural logarithm (base e) of n. If n is negative, an empty string is returned.
exp(n): Returns e (which is approximately 2.71828182845905) raised to the nth power. n may be negative and may contain a decimal point.
abs(n): Absolute value of n.
ceil(n): Returns n rounded up to the nearest integer. For example, ceil(1.2) is 2 and ceil(-1.2) is -1.
floor(n): Returns n rounded down to the nearest integer. For example, floor(1.2) is 1 and floor(-1.2) is -2.
round(n): Returns n rounded to the nearest integer. For example, round(1.4) is 1 and round(1.5) is 2.
sin(n), cos(n), tan(n): Returns the trigonometric sine|cosine|tangent of n which must be expressed in radians.
asin(n), acos(n): Returns the arcsine|arccosine in radians. If n is less than -1 or greater than 1, the function yields an empty string.
atan(n): Returns the arctangent in radians.
CONSTANTS
pi
Archimedes' constant π (~3.1415926535897932384626433832795) which is equal to the circumference of any given circle divided by its diameter.
e
Euler's number e (~2.7182818284590452353602874713527) also known as the exponential growth constant is defined as the value of the following expression:
e := lim n->∞ (1+1/n)**n
phi
The golden ratio φ (~1.618033988749895) is a universal law "in which is contained the ground-principle of all formative striving for beauty and completeness in the realms of both nature and art, and which permeates, as a paramount spiritual ideal, all structures, forms and proportions, whether cosmic or individual, organic or inorganic, acoustic or optical; which finds its fullest realization, however, in the human form." (Adolf Zeising, 1854)
φ := (1+√5)/2
c
The speed of light is usually denoted by c. Light and all other forms of electromagnetic radiation always travel at this speed in empty space (vacuum), regardless of the motion of the source or the inertial frame of reference of the observer. Its value is exactly 299792458 m/s. In the theory of relativity, c interrelates space and time, and appears in the famous equation of mass–energy equivalence E = mc². It is the speed of all massless particles and associated fields in vacuo, and it is predicted by the current theory to be the speed of gravity (that is, gravitational waves) and an upper bound on the speed at which energy, matter, and information can travel.
bigG
The gravitational constant, usually denoted G, is an empirical physical constant involved in the calculation of the gravitational attraction between objects with mass. It appears in Newton's law of universal gravitation and in Einstein's theory of general relativity. It is also known as the universal gravitational constant, Newton's constant, and colloquially Big G. It should not be confused with "little g" (gn), which is the local gravitational field (equivalent to the free-fall acceleration.
gn
The standard gravity, or standard acceleration due to free fall, usually denoted by g0 or gn, is the nominal acceleration of body in a vacuum near the surface of the earth. It is defined to be precisely 9.80665 m/s² or 35.30394 kph/s (~32.174 ft/s² or ~21.937 mph/s). This value was established by the 3rd CGPM (1901, CR 70) and used to define the standard weight of an object as the product of its mass and this nominal acceleration.
delta, alpha
The Feigenbaum constants express ratios in a bifurcation diagram.
δ (delta) (~4.66920160910299067185320382) is the limiting ratio of each bifurcation interval to the next, or between the diameters of successive circles on the real axis of the Mandelbrot set. Feigenbaum originally related this number to the period-doubling bifurcations in the logistic map, but also showed it to hold for all one-dimensional maps with a single quadratic maximum. As a consequence of this generality, every chaotic system that corresponds to this description will bifurcate at the same rate. Feigenbaum's constant can be used to predict when chaos will arise in such systems before it ever occurs. It was discovered in 1975.
α (alpha) (~2.502907875095892822283902873218) is the ratio between the width of a tine and the width of one of its two subtines (except the tine closest to the fold).
These numbers apply to a large class of dynamical systems (for example, dripping faucets to population growth). Both numbers are believed to be transcendental, although they have not been proven to be so. It is an open question as to why this [dimensionless] constant arises so universally and what meaning can be attributed to it
zEta
Apéry's constant ζ (~1.2020569031595942853997381615115)is a number that occurs in a variety of situations. It arises naturally in a number of physical problems, including in the second- and third-order terms of the electron's gyromagnetic ratio using quantum electrodynamics. It also arises in conjunction with the gamma function when solving certain integrals involving exponential functions in a quotient which appear occasionally in physics, for instance when evaluating the two-dimensional case of the Debye model.
gamma
Euler–Mascheroni constant γ (~0.5772156649015328606065120900824) is a recurring constant in number theory. The French mathematician Charles Jean de la Vallée-Poussin proved in 1898 that when taking any positive integer n and dividing it by each positive integer m less than n, the average fraction by which the quotient n/m falls short of the next integer tends to γ as n tends to infinity. Surprisingly, this average doesn't tend to one half. The Euler–Mascheroni constant also appears in Merten's third theorem and has relations to the gamma function, the zeta function and many different integrals and series.
CONVERSIONS
atm
The standard atmosphere is an international reference pressure defined as 101325 Pa and formerly used as unit of pressure. For practical purposes it has been replaced by the bar which is 100000 Pa. The difference of about 1% is not significant for many applications, and is within the error range of common pressure gauges.
The result is given in bar.
in, "
The inch is one of the most common units of length in the United States, and is widely used also in the United Kingdom, and Canada, despite the introduction of metric to the latter two in the 1960s and 1970s, respectively. The inch is sometimes used informally in other Commonwealth nations, such as Australia.
There are 36 inches in a yard and 12 inches in a foot. Effective July 1, 1959, the United States and countries of the British Commonwealth defined the length of the international yard to be exactly 0.9144 metres. Consequently, the international inch is defined to be equal to exactly 25.4 millimetres.
The international standard symbol for inch is "in". In some cases, the inch is denoted by a double prime,which is often approximated by a double apostrophe.
You can use both "in" or a double quotes (") and the result is given in centimeters.
ft, '
A foot (plural: feet) is a non-SI unit of length in a number of different systems including English units, Imperial units, and United States customary units. Its size can vary from system to system, but in each is around a quarter to a third of a meter. The most commonly used foot today is the international foot. There are 3 feet in a yard and 12 inches in a foot.
Effective July 1, 1959 the length of the international yard in the United States and countries of the Commonwealth of Nations was defined as 0.9144 meters. Consequently, the international foot is defined to be equal to exactly 0.3048 meters. This was 2 ppm shorter than the previous U.S definition and 1.7 ppm longer than the previous British definition.
The international standard symbol for a foot is "ft". In some cases, the foot is denoted by a prime, which is often approximated by an apostrophe, and the inch by a double prime; for example, 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″ or 2′4″. This use can cause confusion, because the prime and double prime are also international standard symbols for arcminutes and arcseconds.
You can use both "in" or an apostrophe (') and the result is given in meters.
mi
In contemporary English, a mile most commonly refers to the statute mile of 5280 feet (1760 yards, or 1609.344 metres), the survey mile of 5280 survey feet (1609.3472 metres) or the nautical mile of 1852 metres (6076.12 ft).
The use of statute miles as a unit of measurement is largely used in the United States and the United Kingdom. There are many other historical miles and similar units in other systems translated as miles in English, varying between one and fifteen kilometres.
The statute mile was defined by an English Act of Parliament in 1592 as being 1760 yards (5280 feet, about 1609 metres) but the exact conversion of the mile to SI units depends on which definition of the yard is in use. Different English-speaking countries maintained independent physical standards for the yard that were found to differ by small, but measurable, amounts and even to slowly shorten in length. The United States redefined the U.S. yard in 1893, but this resulted in U.S. and Imperial units with the same names having very slightly different values. The difference was resolved in 1959 with the definition of the international yard in terms of the metre by Australia, Canada, New Zealand, South Africa, the United Kingdom, and the United States. The "international mile" of 1760 international yards is exactly 1609.344 metres.
The result is given in kilometers.
yd
A yard is a unit of length in several different systems. It is used as the standard unit of field-length measurement in American, Canadian, Association football, and Cricket. Yards are also used in road signs on roads in the United Kingdom and the United States to specify short distances. It is equal to 3 feet or 36 inches, although its length in SI units varied slightly from system to system. The most commonly used yard today is the international yard, which, in Australia, Canada, New Zealand, South Africa, the United Kingdom, and the United States, is legally defined to be exactly 0.9144 metre.
That is, the result is given in meters.
oz
The avoirdupois ounce is the most commonly used ounce today. It is defined to be one sixteenth of an avoirdupois pound; and the avoirdupois pound is defined as 7000 grains. One ounce is therefore equal to 437.5 grains.
In 1958 the United States and countries of the Commonwealth of Nations agreed to define the international avoirdupois ounce to be exactly 0.45359237⁄16 kg (28.349523125g) by definition.
The ounce is commonly used as a unit of mass in the United States. On January 1, 2000, it ceased to be a legal unit of measure within the United Kingdom for economic, health, safety or administrative purposes but remains a familiar unit.
The result is given in grams.
gr
A grain is a unit of measurement of mass that is based upon the mass of a single seed of a cereal. In medieval times the average masses of wheat and barley grain were used to define units of mass, with the troy grain based on barley.
Since 1958, the grain measure has been defined in terms of units of mass as precisely 64.79891 milligrams.
The result is given in grams.
lb
The pound or pound-mass is a unit of mass used in the imperial, United States customary and other systems of measurement. A number of different definitions have been used and the most common today is the international avoirdupois pound which is legally defined as exactly 0.45359237 kilograms since 1 July 1959
The unit is descended from the Roman libra (hence the abbreviation "lb"); the name pound is a Germanic adaptation of the Latin phrase libra pondo, 'a pound weight'.
Usage of the unqualified term pound reflects the historical conflation of mass and weight resulting from the near uniformity of gravity on Earth. This accounts for the modern distinguishing terms pound-mass and pound-force.
The result is given in kilograms.
rad
The radian is the standard unit of angular measure, used in many areas of mathematics. It describes the plane angle subtended by a circular arc as the length of the arc divided by the radius of the arc.
The result is given in degrees.
deg
A degree is a measurement of plane angle, representing 1⁄360 of a full rotation. Therefore, one degree is equivalent to π/180 radians and the result is given in radians.
°C
Celsius is a scale and unit of measurement for temperature. It is named after the Swedish astronomer Anders Celsius (1701–1744), who developed a similar temperature scale two years before his death.
From 1744 until 1954, 0°C was defined as the freezing point of water and 100°C as the boiling point of water, both at a pressure of one standard atmosphere with mercury being the working material. Although these defining correlations are commonly taught in schools today, by international agreement the unit "degree Celsius" and the Celsius scale are currently defined by two different points: absolute zero, and the triple point of VSMOW (specially prepared water). This definition also precisely relates the Celsius scale to the Kelvin scale, which defines the SI base unit of thermodynamic temperature (symbol: K). Absolute zero, the hypothetical but unattainable temperature at which matter exhibits zero entropy, is defined as being precisely 0K and −273.15°C. The temperature value of the triple point of water is defined as being precisely 273.16K and 0.01°C.
This definition fixes the magnitude of both the degree Celsius and the kelvin as precisely 1 part in 273.16 (approximately 0.00366) of the difference between absolute zero and the triple point of water. Thus, it sets the magnitude of one degree Celsius and that of one kelvin as exactly the same. Additionally, it establishes the difference between the two scales' null points as being precisely 273.15 degrees Celsius.
So, the result is given in °F :)
°F
Fahrenheit is the temperature scale proposed in 1724 by, and named after, the German physicist Daniel Gabriel Fahrenheit (1686–1736).
On the Fahrenheit scale, the freezing point of water is 32 degrees Fahrenheit (°F) and the boiling point 212°F (at standard atmospheric pressure), placing the boiling and freezing points of water exactly 180 degrees apart.
According to a letter Fahrenheit wrote to his friend Herman Boerhaave, his scale was built on the work of Ole Rømer, inwhich, brine freezes at 0 degrees, ice melts at 7.5 degrees, body temperature is 22.5, and water boils at 60 degrees. Fahrenheit multiplied each value by four in order to eliminate fractions and increase the granularity of the scale. He then re-calibrated his scale using the melting point of ice and normal human body temperature (which were at 30 and 90 degrees); he adjusted the scale so that the melting point of ice would be 32 degrees and body temperature 96 degrees, so that 64 intervals would separate the two, allowing him to mark degree lines on his instruments by simply bisecting the interval six times.
Fahrenheit observed, somewhat incorrectly, that water boils at about 212 degrees using this scale. Later, other scientists decided to redefine the degree slightly to make the freezing point exactly 32°F, and the boiling point exactly 212°F or 180 degrees higher. It is for this reason that normal human body temperature is approximately 98°F (oral temperature) on the revised scale.
The Fahrenheit scale was the primary temperature standard for climatic, industrial and medical purposes in some English-speaking countries until the 1960s. But, Even if has been replaced by the Celsius scale in most countries, it remains the official scale of the United States and Belize and is retained as a secondary scale in the United Kingdom. The resistance to the Celsius system in the U.S., is based on the larger size of each degree Celsius (resulting in the need for decimals where integer Fahrenheit degrees were adequate for much technical work). Another reason is the lower zero point in the Fahrenheit system which reduces the number of negative signs when measurements such as weather data were averaged.
the result is given in °C.
Function and tests:
Code:
t1 := "(-1-5)(60/(2πrad))"
t2 := "(5+1/4)''"
t3 := "cos(π √(16^(1/2))/2)(-1-(-4cos(0))-(2exp(0)))"
t4 := "e*ln(exp(1e-3))"
t5 := "π(212°F)*1e3/100000"
t6 := "(0x10+0x70<<2 and 512)>>9"
t7 := "2cos π (exp 0)"
msgbox % t1 " = " Calc(t1)
msgbox % t2 " = " Calc(t2)
msgbox % t3 " = " Calc(t3)
msgbox % t4 " = " Calc(t4)
msgbox % t5 " = " Calc(t5)
msgbox % t6 " = " Calc(t6)
msgbox % t7 " = " Calc(t7)
Calc(s, init=1)
{
Static f := "sqrt|log|ln|exp|sin|cos|tan|asin|acos|atan|abs|ceil|floor|round",
o := "\*\*|\^|!|//|/|\\|\*|\+|\-|mod|<<|>>|and|xor|or",
const := Object("e", 2.7182818284590452353602874713527 ; e
, "pi", 3.1415926535897932384626433832795, "π", 3.1415926535897932384626433832795 ; pi
, "phi", "(1+sqrt5)/2", "φ", "(1+sqrt5)/2" ; phi (golden ratio)
, "alpha", 2.502907875095892822283902873218, "α", 2.502907875095892822283902873218 ; Feigenbaum alpha
, "delta", 4.66920160910299067185320382, "δ", 4.66920160910299067185320382 ; Feigenbaum delta
, "zEta", 1.2020569031595942853997381615115, "ζ", 1.2020569031595942853997381615115 ; Apéry zeta
, "gamma", .5772156649015328606065120900824, "γ", .5772156649015328606065120900824 ; Euler–Mascheroni gamma
, "gn", 9.80665 ; standard gravity (m/s²)
, "bigG", "6.67428*10^-11" ; Newtonian constant of gravitation (m3/kg/s²)
, "c", 299792458 ; speed of light (m/s)
, "atm", "*1.01325" ; standard atmosphere pressure (bar)
, "in", "*2.54", "\x22", "*2.54", "ft", "*.3048", "'", "*.3048" ; inch (cm), feet (m)
, "mi", "*1.609344", "yd", "*0.9144" ; mile (km), yard (m)
, "oz", "*28.349523125", "lb", "*.45359237", "gr", "*.06479891" ; ounce (g), pound (kg), grain (g)
, "rad", "*57.295779513082320876798154814105" ; radian -> degree
, "deg", "*.01745329251994329576923690768489" ; degree -> radian
, "°C", "*1.8+32" ; °C -> °F
, "°F", "*.5555555555555556-17.7777777777777778" ; °F -> °C
, "√", "sqrt")
if init {
s := RegExReplace(s, "\s", "") ; remove spaces, tabs, etc.
if RegExMatch(s, "^(b|d|h)?.*(0x)", c) {
s := c1 == "b" || c1 == "d" || c1 == "h" ? SubStr(s, 2) : s
c1 := c1 ? c1 : c2 == "0x" ? "h" : ""
While RegExMatch(s, "i)(.*)(0x[a-f\d]*)(.*)", r) ; hex -> dec
s := r1 . r2+0 . r3
}
While RegExMAtch(s, "(.*)(²[01]*)(.*)", r) { ; bin -> dec
c1 := c1 ? c1 : "b"
r := 0, r2 := SubStr(r2, 2), r4 := StrLen(r2)
Loop, Parse, r2
r += A_LoopField ? 2**(r4-A_Index) : 0
s := r1 . r . r3
}
s := RegExReplace(s, "(\d)e(\-?\d)", "$1*10^$2") ; scientific -> dec
s := RegExReplace(s, "([\d\)πφαδζγeGc]|gn|pi|phi|alpha|delta|zEta|gamma)([\(πφαδζγG√c]|gn|pi|phi|alpha|delta|zEta|gamma|" f ")", "$1*$2")
s := RegExReplace(s, "(" f ")", "$U1") ; uppercase function names
For k, v in const
s := RegExReplace(s, "(" k ")", v)
}
While RegExMatch(s, "(.*)\(([^\(\)]+)\)(.*)", t) ; evaluate (...)
s := t1 . Calc(t2, 0) . t3
fm := A_FormatFloat
SetFormat, Float, 0.16
Loop, Parse, f, |
While RegExMatch(s, "i)(" A_Loopfield ")(\-?[\d\.]+)", t)
StringReplace, s, s, %t1%%t2%%t3%, % %t1%(t2)
Loop, Parse, o, |
While RegExMatch(s, "(\-?[\d\.]+)(" A_Loopfield ")(\-?[\d\.]*)", t) {
if (t2=="!") {
r := 1
Loop, % abs(t1)
r *= A_Index
r := t1/abs(t1) * r . t3
}
else
r := t2 == "**" ? t1 ** t3 : t2 == "^" ? t1 ** t3
: t2 == "*" ? t1 * t3 : t2 == "/" ? t1 / t3
: t2 == "//" ? t1 // t3 : t2 == "\" ? t1 // t3
: t2 == "mod" ? mod(t1, t3)
: t2 == "+" ? t1 + t3 : t2 == "-" ? t1 - t3
: t2 == "<<" ? t1 << t3 : t2 == ">>" ? t1 >> t3
: t2 == "and" ? t1 & t3 : t2 == "xor" ? t1 ^ t3 : t2 == "or" ? t1 | t3
: 0
StringReplace, s, s, %t1%%t2%%t3%, %r%
}
SetFormat, Float, %fm%
if (c1=="h") {
fm := A_FormatInteger
SetFormat, Integer, H
s := "0x" SubStr(Round(s)+0, 3)
SetFormat, Integer, %fm%
return s
}
if (c1=="b") {
r := "", s *= 2
While (s := s // 2)
r := Mod(s, 2) . r
return "²" r
}
return RegExReplace(RegExReplace(s, "(\d\.0*[1-9]+)0+$", "$1"), "\.0+$", "")
}