PhysicalValues/en
Notice: the physical values package as described here is still considered "work in progress" and provided as a preview feature. Please report any errors or inconveniences (or wishes) to exept.
Inhaltsverzeichnis
- 1 Introduction
- 2 Motivating Examples
- 3 Physic Package Loading
- 4 Programming Language API
- 5 Base Units
- 6 Derived Units
- 7 SI Prefix
- 8 Unit API
- 9 Per Unit Detailed API
- 9.1 Mass
- 9.2 Length
- 9.3 Angle
- 9.4 Temperature
- 9.5 Frequency
- 9.6 Energy
- 9.7 Power
- 9.8 Force
- 9.9 Area
- 9.10 Volume
- 9.11 Velocity (Speed)
- 9.12 Acceleration
- 9.13 Pressure
- 9.14 Voltage
- 9.15 Electric Current
- 9.16 Electric Resistance
- 9.17 Electric Capacitance
- 9.18 Electric Charge
- 9.19 Inductance
- 9.20 LuminousIntensity
- 9.21 Luminance
- 9.22 MagneticFlux
- 9.23 MagneticFluxDensity
- 9.24 Mass Density
- 10 Defining Additional Unit Converters
- 11 Arithmetic
- 12 Formula Evaluation
- 13 Providing additional Formulas
- 14 Nature Constants
- 15 Equation Solving
- 16 Measured Physical Values
- 17 Physical Values and Numeric Precision
- 18 Physical Values in Activity Diagrams
- 19 Physical Values in Elementary Code
- 20 Math Language Workspace
- 21 Examples
Introduction[Bearbeiten]
In the past, a number of big projects failed or went completely out of budget due to misinterpretations of data. An example well known to insiders (but not named here) lead to millions of loss due to some misinterpretation of metric versus imperial values in documentation and software.
Expecco supports values with units, to represent physical values such as length, acceleration, area, volume, mass, temperature, electric current etc.
Physical values are useful for a nicer presentation of measurement values (eg. in a report) and to convert between unit systems (eg. metric vs. imperial vs. US). They can also make elementary code which computes physical values more readable and more robust. And if the correct unit is returned from an expression, you know that you used the correct formula (or at least: not completely wrong).
Physical values are implemented by the underlying Smalltalk system and can be used both in Smalltalk and in JavaScript elementary blocks. Similar public domain packages might be available for Node and Python actions, and these can be installed with "npm" or "pip".
However, there are currently no plans to transparent support exchange of physical values between expecco and Python, Node or Java. If required, these should be passed as composite "{ amount:xxx unit:xxx }" objects and converted in the bridge as required. Sorry, but there exists as yet no commonly used encoding standard for such data (eg. in JSON).
The following document describes the programmer's API for elementary Smalltalk and JavaScript actions. Corresponding types are found in datatype menus under the "Physics" group.
Motivating Examples[Bearbeiten]
Example1: Time to Load a Cap (i.e. RC time constant)[Bearbeiten]
You want to compute how long it takes to load a 100uF capacitor, given a 5V supply and a current limiting resistor with 100 kOhm?
The electric charge (in Coulomb) transported through a wire is:
charge = I*t (I = current in Ampere; t in Seconds)
and the charge (in Coulomb) of a capacitor is:
charge = C*U (C = capacity in Farad; U = voltage)
We can immediately compute the electrical charge (in Coulomb) with the formula (C*U):
(5 volt * 100 micro farad)
and get the result:
(1/2000) C
Notice that the above is Smalltalk syntax, and can be written exactly like that in a Smalltalk action.
We can also compute the current through the loading resistor (I = U / R) as:
5 volt / 100 kilo ohm
and get the result:
50 µA
To compute the time, equate and rearrange the above formulas:
(C * U) t = ------- I
with I = U / R, we get:
(C * U) t = ------- (U / R)
in Smalltalk (*):
t := (5 volt * 100 micro farad ) / (5 volt / 100 kilo ohm)
and will get the time for t as:
10s
In other words, Smalltalk automatically found the correct result unit from the above computation and figured, that the result must be a time duration given in Seconds.
(*) obviously, we could have further simplified the formula, or ask expecco to simplify it for us with:
(Physic::Expression simplify:'(U * C) / (U / R)') simplified
- which gives the result:
C * R
- So, we could have also computed:
t := 100 micro farad * 100 kilo ohm
- and also get the same 10 seconds as result.
Example2: Signal Rise Time[Bearbeiten]
Of course, you may also get the time with a given delta-voltage and current flow. From the formula:
I = C * ΔV / Δt.
we get:
Δt = C * ΔV / I
As an example, if an output pin of an IC drives 10mA, and it is connected to an input pin with 100pF input capacitance to ground, it will take:
100 pico farad * 5 volt / 10 milli ampere
to get it from 0V to 5V (in this case: 50ns).
Example3: Bandpass Filter Frequency[Bearbeiten]
A filter's frequency is computed as:
1 f = ------------ 2*π*R*C
What is the frequency, given 1 Megaohm and 0.1 Microfarad as values?
In Smalltalk:
|r c f| r := 1 mega ohm. c := 0.1 micro farad. f := 1 / (2*Float pi * r * c)
result:
f = 1.59154943091895 Hz
Physic Package Loading[Bearbeiten]
If you have an older expecco version, the physic packages (stx:goodies/physic/units
for units and stx:goodies/physic/formula
for formula parsing) may not be already loaded.
If not, either add it to the list of required packages of your test suite or evaluate:
Smalltalk requirePackage:'stx:goodies/physics/units'. Smalltalk requirePackage:'stx:goodies/physics/formula'.
in either an elementary action or in the startup file ("expeccoStart.rc
").
All physic classes will be found in the "Physic
" namespace
(i.e. class names are prefixed with "Physic::
" as in "Physic::Energy
" or "Physic::Volume
").
Programming Language API[Bearbeiten]
As you'll have noticed, Smalltalk has a convenient syntax, for this kind of framework: you can immediately write code like:
1 kilo meter / 10 minutes
to compute a velocity.
Due to the fact that the builtin Javascript also allows for numbers to be treated like objects, the same code written in JavaScript still looks somewhat readable: "1.kilo().meter() / 10.minutes()
, although the parentheses make the code somewhat ugly.
All code fragments in the following document are written in Smalltalk syntax.
Base Units[Bearbeiten]
All base units are measured in their corresponding SI standard units and print with an appropriate scaling prefix.
For example, a mass, which has a base unit of kilogram ("kg") will print itself as "kg', 'mg', 'µg' etc. depending on its magnitude. Explicit converters can be used to enforce a particular unit printing (eg. if you insist on printing a mass in pounds, in grams, etc.) or if you want to enforce a particular scaling SI prefix (eg. to enforce printing output in "cm" instead of "m" or "mm").
See examples below on how those converters affect the printout of a value.
Independent from any enforced print format, the internal representation of physical values is always using base unit amounts (i.e. SI units).
Base units are:
Unit Name Smalltalk Description ----------------------------------------- s Second second time m Meter meter length (*) kg Kilogram kilogram mass A Ampere ampere electric current K Kelvin kelvin temperature mol Mole mole amount of substance cd Candela candela luminous intensity
To get a constant physical value in your Smalltalk code, write a number followed by the unit name (in lowercase). For example:
1 ampere 10 candela 5 kilogram
(in other words: there are a number of methods defined in the Number class, which take the receiver and construct a corresponding unit instance from it. These methods are named after the SI unit names).
Derived Units[Bearbeiten]
Additional derived units are:
Unit Name Smalltalk Description ------------------------------------------------------------- V Volt volt voltage Hz Hertz hertz frequency m/s Meter per Second meterPerSecond speed, velocity m/s² m/s per Second meterPerSecondPerSecond acceleration m² Square Meter squareMeter area m³ Cubic Meter cubicMeter volume pa Pascal pascal pressure W Watt watt power N Newton newton force J Joule joule energy Ω Ohm ohm electric resistance C Coulomb coulomb electric charge F Farad farad electric capacitance rad Radian radian angle
Plus possibly more, by the time you read this.
There are a number of less frequently used derived units, for which no Smalltalk shortcut exists.
These might result from computations with physical values or be instantiated by sending explicit constructor messages to the unit (instead of sending a message to a number).
These are described below.
SI Prefix[Bearbeiten]
Numbers (in Smalltalk and JavaScript) can be scaled by an SI prefix message.
Thus, when combining a unit message with a scaled number, we get a scaled physical value.
For example, without SI prefix, we get:
1 gram => '1 g'
whereas with a 'micro' prefix, the result is:
1 micro gram => '1 µg'
or:
1 hecto liter => '100 liter'
The corresponding JavaScript code is similar, but slightly less elegant looking due to the required periods and parentheses:
1.gram() 1.micro().gram() 1.hecto().liter()
Possible scaling prefixes are:
yocto 1E-24 1 / 1000000000000000000000000 zepto 1E-21 1 / 1000000000000000000000 atto 1E-18 1 / 1000000000000000000 femto 1E-15 1 / 1000000000000000 pico 1E-12 1 / 1000000000000 nano 1E-9 1 / 1000000000 micro 1E-6 1 / 1000000 milli 1E-3 1 / 1000 centi 1E-2 1 / 100 deci 1E-1 1 / 10 deca 1E+1 10 hecto 1E+2 100 kilo 1E+3 1000 mega 1E+6 1000000 giga 1E+9 1000000000 tera 1E+12 1000000000000 peta 1E+15 1000000000000000 exa 1E+18 1000000000000000000 zetta 1E+21 1000000000000000000000 yotta 1E+24 1000000000000000000000000
You can combine the SI scale with a unit, as in:
1 kilo meter 1 micro ampere 1 mega watt 1 pico farad 1 exa bytes
For some common units, additional shortcuts exist:
1 kiloMeter ; centiMeter ; milliMeter ; microMeter ; nanoMeter 1 milliGram ; microGram 1 milliAmpere ; microAmpere 1 milliVolt ; microVolt 1 kiloByte ; megaByte ; teraByte ; peraByte ; exaByte
In addition to the above listed powers-of-10 scaling prefixes, there are also powers-of-2 prefixes, which are usually only used with byte amounts:
kibi 2ˆ10 1024 mebi 2ˆ20 1048576 (same as "1024 * 1024" or "1024 kibi") gibi 2ˆ30 1073741824 (same as "1024 * 1024 * 1024" or "1024 mebi) tebi 2ˆ40 1099511627776 pebi 2ˆ50 1125899906842624 exbi 2ˆ60 1152921504606846976 zebi 2ˆ70 1180591620717411303424 yobi 2ˆ80 1208925819614629174706176
For the kibi scaler, you can use the shortcut:
1 kibiByte
all others need to be combined, as in:
1.0 mebi byte
Unit API[Bearbeiten]
Units vs. Values[Bearbeiten]
Internally, PhysicalValues are represented as a pair of a PhysicalUnit and an amount. PhysicalUnit may be either one of the above listed base units (i.e. SI base units), or a scaling/converting unit (eg. Inches or Hectare but also MilliMeter).
You can get a unit (in contrast to a value) by sending one of the unit-messages to the Physic::PhysicalUnit class (i.e. the class named "PhysicalUnit" in the "Physic" namespace).
For example, " Physic::PhysicalUnit energy
" will give you the "Energy" class which describes values with the "Joule" SI-unit.
Conversion units are retrieved by asking one such unit for another, by sending it a corresponding getter message.
For example, we can ask the Energy class for a converting class named "Calories" with " Physic::PhysicalUnit energy calories
On the basic level, PhysicalValue are created by sending the "unitAmount:
" message to a Unit (however, there are convenient and more readable messages implemented in the Number hierarchy, which allow for shorter code; this is described below).
For example:
Physic::PhysicalUnit energy unitAmount:100
generates an energy instance of 100 joule.
The argument of the "unitAmount:
" call is always given in units of the receiver unit, whereas the alternative constructor named "baseUnitAmount:
" expects the argument to be in the underlying base unit (i.e. one of the SI units).
This makes no difference for the base SI units, but is relevant, if you deal with conversion units (eg. imperial units) as described later. Thus,
Physic::PhysicalUnit energy calories unitAmount:100
will create an energy instance of 100 calories (which will print itself as calories), whereas:
Physic::PhysicalUnit energy calories baseUnitAmount:100
will create an energy instance of 100 joule (which will print itself as calories).
Notice, that the "energy
" message is a facade getter method of Physic::PhysicalUnit (i.e. the class named "PhysicalUnit" in the "Physic" namespace). It retrieves the Energy class, which is actually named "Physic::Energy" and is also located in the Physic namespace.
Base SI Units[Bearbeiten]
Getters for well known units are:
Physic::PhysicalUnit acceleration Physic::PhysicalUnit amountOfSubstance Physic::PhysicalUnit angle Physic::PhysicalUnit area Physic::PhysicalUnit currentDensity Physic::PhysicalUnit electricCapacitance Physic::PhysicalUnit electricCharge Physic::PhysicalUnit electricConductance Physic::PhysicalUnit electricCurrent Physic::PhysicalUnit electricResistance Physic::PhysicalUnit energy Physic::PhysicalUnit force Physic::PhysicalUnit frequency Physic::PhysicalUnit inductance Physic::PhysicalUnit length Physic::PhysicalUnit luminousIntensity Physic::PhysicalUnit mass Physic::PhysicalUnit massDensity Physic::PhysicalUnit power Physic::PhysicalUnit pressure Physic::PhysicalUnit specificVolume Physic::PhysicalUnit temperature Physic::PhysicalUnit time Physic::PhysicalUnit velocity Physic::PhysicalUnit voltage Physic::PhysicalUnit volume Physic::PhysicalUnit knownUnits
The last returns a collection of all known units (there are actually more than listed above).
The very most used units are directly accessible via a global under the Physic namespace:
Physic::Mass Physic::Length Physic::Energy Physic::Velocity etc.
For common units, additional instance creation protocol is provided in the Number class. Eg.:
100 joules
will generate the same as:
(Physic::PhysicalUnit energy) baseUnitAmount:100
which is the same as:
Physic::Energy baseUnitAmount:100
which (for base units) is the same as:
Physic::Energy unitAmount:100
The additional Number-protocol is described below.
Printing Unit Values[Bearbeiten]
When printed, physical values will scale and use an SI prefix as appropriate.
For example, by default, a value of 100 millimeter will print as "100 mm" instead of "0.1 m" (remember: meter is the underlying SI base unit).
This print behavior can be changed by converting to an explicit converted unit via one of the "asXXX
" messages listed below. However, the SI base unit amount will be kept internally and used in arithmetic operations. Thus, eg. when adding a meter with inches, an SI meter value will be generated, and the result will be presented in the same unit as the receiver (first operand).
For example:
1 inch
will still print as meter (actually as '25.4 mm'), whereas:
1 inch asInches
will print itself as inches. And both:
1 meter + 1 inch asInches 1 meter + 1 inch
will print as meter ('1.0254 m'), whereas:
1 inch asInches + 1 meter
will print as inches.
Converting Units[Bearbeiten]
In addition to predefined converting units, as listed below, it is also possible to define custom units, with different (customizable) print behavior (more on that below).
Predefined Converting Units[Bearbeiten]
Some such custom units are already predefined; for example, to represent imperial units, conversion units derived from mass are found (among others) as:
Physic::PhysicalUnit mass ounces (or Physic::Mass ounces) Physic::PhysicalUnit mass pounds (or Physic::Mass pounds)
and length units as:
Physic::PhysicalUnit length inches (or Physic::Length inches) Physic::PhysicalUnit length feet Physic::PhysicalUnit length yards
Thus, you can create unit values which print themself (eg.) in imperial units:
yardsUnit := Physic::Length yards. distance := yardsUnit unitAmount:10
will give you 10 yards, which prints itself as such ('10 yd').
Whereas:
distance2 := yardsUnit baseUnitAmount:10
will create a distance of 10 meters (the underlying base unit), which prints itself in yards.
Be careful to not confuse unit amounts with base unit amounts, and be reminded that the internal storage representation of all units is always in SI base units. The conversion is only performed when such values are printed.
In general, you can ask most base units for common conversion units (which are the units used by the asXXX converters below).
These can also be used to instantiate instances or for conversion.
Eg.
Physic::Mass ounces unitAmount:1
returns 1 ounce (which prints itself as such), and:
1 kiloGram as:(Physic::Mass ounces)
returns 32.27 ounces (which also prints itself as such).
Predefined Scaling Units[Bearbeiten]
By default, the unit chooses itself, how values are scaled when printing. For example, "(1/1000.0) kilo gram" will print itself as "1 g", although the underlying baseUnit is kilogram.
You can force a particular scale either by using one of the scale-converting units, eg:
someUnit asMilliUnit baseUnitAmount:scalarValueInBaseUnits
or by giving it a unit amount:
someUnit asMilliUnit unitAmount:scalarValueInUnits
or by converting a unit-value:
someUnitValue asMilliUnitValue
Again, scalarValueInBaseUnits is in base-units (kg, N, Hz,...), whereas scalarValueInUnits is in scaled-units (mg, kN, Mhz,...).
For example:
0.01 kilo gram => prints as "10 g" Physic::Mass baseUnitAmount:0.01 => prints as "10 g" Physic::Mass milliUnit baseUnitAmount:0.01 "/ specified in kg here => prints as "10000 mg" Physic::Mass milliUnit unitAmount:100 "/ specified in mg here => prints as "100 mg"
To get a scaling unit from a given base unit (such as "Mass", "Length", "Volume", etc.) or from a given derived Unit (such as "Volume liters"), apply one of the following:
aUnit picoUnit aUnit nanoUnit aUnit microUnit aUnit milliUnit aUnit deciUnit aUnit hectoUnit aUnit kiloUnit aUnit megaUnit aUnit gigaUnit aUnit teraUnit
To convert a given value (as opposed to a unit as above), use one of:
aValue asPicoUnitValue aValue asNanoUnitValue aValue asMicroUnitValue aValue asMilliUnitValue aValue asDeciUnitValue aValue asHectoUnitValue aValue asKiloUnitValue aValue asMegaUnitValue aValue asGigaUnitValue aValue asTeraUnitValue
Thus if you want to force any physical value to print itself in its 'milli' unit, use:
i := 1 ampere. m_i := i asMilliUnitValue.
of course, you can also use the unit-specific converters; in this case:
m_i := i asMilliAmperes
or the above example:
0.01 kilo gram asMilliUnitValue 0.01 kilo gram asMilliGrams
The asXXXUnitValue methods work on any physical value, whereas the unit-specific methods will only work on the appropriate unit value. Thus, the later are preferable, as they provide an additional quality check for your code. For a list of unit-specific converters, see below.
Predefined Wellknown Units[Bearbeiten]
The base SI units Mass, Length, Force, etc. can be directly accessed from the Physic namespace as Physic::<nameOfUnit>
.
Other derived and less frequently units can be accessed either via getters from the Physic::PhysicalUnit class, or by asking it via Physic::PhysicalUnit unitNamed:'nameOfUnit'
.
A list of known units is retrieved with Physic::PhysicalUnit knownUnits
.
Mass:[Bearbeiten]
- Physic::Mass
The base unit ("kg"). - Physic::Mass ounces
Returns the "Ounces" unit; a converting unit. - Physic::Mass pounds
Returns the "Pounds" converting unit. - Physic::Mass troyOunces
Returns the "TroyOunces" converting unit. - Physic::Mass carat
Returns the "Carat" converting unit. - Physic::Mass atomicMassUnits
Returns the "AtomicMassUnits" converting unit. - more mass converting units are returned by: daltons, grams, kiloGrams, kiloTonnes, megaTonnes, milliGrams, microGrams, nanoGrams, tonnes.
- You may wonder what the kiloGrams converting unit is useful for, as the base unit's amount is already in Kilograms; the difference is that the base unit will print values with a prefix (milli, micro, kilo etc.) whereas the kiloGram converting unit will always print kilograms.
AmountOfSubstance:[Bearbeiten]
- Physic::AmountOfSubstance
The base unit is "mol". - Physic::AmountOfSubstance particles
Returns the (number of) "Particles" converting unit.
Angle:[Bearbeiten]
- Physic::Angle
The base SI unit. Prints as "rad". - Physic::Angle degrees
Returns the "Degrees" converting unit. - Physic::Angle gon
Returns the "Gon" converting unit. - Physic::Angle arcMin
Returns the "ArcMinutes" converting unit. - Physic::Angle arcSec
Returns the "ArcSeconds" converting unit.
Area:[Bearbeiten]
- Physic::Area
The base SI unit. Prints as square meters.
- converting units are returned by asking an Area unit with one of: acre, are, hectare, squareFoot, squareKiloMeters, squareMeter, squareMiles.
Bits & Bytes:[Bearbeiten]
- Physic::Bytes
The bytes unit. Not really SI, but useful for printing file sizes. - Physic::Bits
The bits unit. Not really SI, but useful for printing transmission speeds (bits/s).
- converting units are present for mega/mebi, kilo/kibi, etc.
Electric Charge:[Bearbeiten]
- Physic::ElectricCharge
The base SI unit. Prints as Coulomb.
- converting units are returned by: ampereSeconds, ampereHours, elementaryCharges.
Energy:[Bearbeiten]
- Physic::Energy
The base SI unit. Prints as Joules.
- converting units are returned by: btu, calories, kiloCalories, electronVolts, kiloWattHours, megaWattHours, gigaWattHours, kiloJoules, megaJoules, gigaJoules.
Force:[Bearbeiten]
- converting units are returned by: gramForce, newtons, poundForce, tonForce
Frequency:[Bearbeiten]
- converting units are returned by: kiloHertz, megaHetz, gigahertz.
Length:[Bearbeiten]
- converting units are returned by: feet, feetAndInches, inches, kiloMeters, landMiles, lightSeconds, lightYears, meters, micrometers, milliMeters, nanoMeters, nauticalMiles, yards.
Power:[Bearbeiten]
- converting units are returned by: dBW, dBm, gigaWatt, kiloWatt, megaWatt, milliWatt
Pressure:[Bearbeiten]
- converting units are returned by: bar, hectoPascal, pascal, psi
Temperature:[Bearbeiten]
- converting units are returned by: celsius, fahrenheit, rankine
Velocity:[Bearbeiten]
- converting units are returned by: kiloMetersPerHour, knots, metersPerHour, milesPerHour
Volume:[Bearbeiten]
- converting units are returned by: centiLiters, cubicInches, cubicMeters, fluidOuncesGB, fluidOuncesUS, gallonsGB, gallonsUS, hectoLiters, liters, milliLiters
Per Unit Detailed API[Bearbeiten]
Mass[Bearbeiten]
Mass is measured in units of Kilogram, and the default printing is in "kg", "g", "mg", "ng" or whatever the print function considers appropriate.
The following operations return an instance of a mass (i.e. a value with a unit of "Mass") all of which will print themself as base units:
Instance Creation[Bearbeiten]
- number kiloGram
Generates a mass-value of n kilograms.
Same asn kilo gram
(using SI prefix).
- number gram
Generates a mass-value of n grams.
- number milliGram
Generates a mass-value of n milligrams.
Same asn milli gram
.
- number microGram
Generates a mass-value of n micrograms.
Same asn micro gram
.
- number pounds
Generates a mass-value of n pounds. A pound is defined as 453.59237 gram.
- number ounces
Generates a mass-value of n ounces. These are british (imperial) ounces (28.35 g)
- number troyOunces
Generates a mass-value of n troy ounces. These are used with metals (esp. gold) (31.1034768 g)
Unit Conversion[Bearbeiten]
- aMass asGrams
Returns the original mass in a converted unit which enforces explicit printing in grams (i.e. without any SI scaling prefix).
- aMass asNanoGrams
Same, but enforces explicit printing in nanograms ("ng").
- aMass asMicroGrams
Enforces explicit printing in micrograms ("µg").
- aMass asMilliGrams
Enforces explicit printing in milligrams ("mg").
- aMass asKiloGrams
Enforces explicit printing in kilograms ("kg").
- aMass asTonnes
Enforces explicit printing in (metric) tonnes ("t").
- aMass asKiloTonnes
Enforces explicit printing in (metric) kilotonnes ("kt").
- aMass asMegaTonnes
Enforces explicit printing in (metric) megatonnes ("Mt").
- aMass asPounds
Enforces explicit printing in pounds ("lb") One pound is 453.59237 g.
- aMass asCarat
Enforces explicit printing in carat ("ct"). 1 carat is 200mg.
- aMass asOunces
Enforces explicit printing in ounces ("oz"). These are british (imperial) ounces (28.35 g)
- aMass asTroyOunces
Enforces explicit printing in troy ounces ("oz t"). These are used with metals (31.103 g)
- aMass asAtomicMassUnits
Enforces explicit printing in atomic mass units ("amu"). One amu is 1.660539066605e-27Kg.
Length[Bearbeiten]
Length is measured in Meters, and the default printing is in "m", "km", "mm", "nm" or whatever the print function considers appropriate.
Instance Creation[Bearbeiten]
- number meter
Generates a length-value of n meters.
- number centiMeter
Generates a length-value of n centimeters.
Same asn centi meter
.
- number milliMeter
Generates a length-value of n millimeters.
Same asn milli meter
.
- number microMeter
Generates a length-value of n micrometers.
Same asn micro meter
.
- number nanoMeter
Generates a length-value of n nanometers.
Same asn nano meter
.
- number kiloMeter
Generates a length-value of n kilometers.
Same asn kilo meter
.
- number inch
Generates a length-value of n inches. An inch is 25.4 mm.
- number inches
Same as inch above (for readability)
- number feet
Generates a length-value of n feet. A foot is 12 inches or 0.3048 m.
- number yards
Generates a length-value of n yards. A yard is 36 inches or 0.9144 m.
- number landMiles
Generates a length-value of n land miles. A land mile is 5280 feet or 1609.344 m.
- number nauticalMiles
Generates a length-value of n nautical miles. A nautical mile is 1852 m.
- number chineseMiles
Generates a length-value of n chinese miles. A Chinese mile is 500 m.
- number astronomicalUnits
Generates a length-value of n astronomical units. An au is 149597870.7 km.
- number lightSeconds
Generates a length-value of n lightseconds. A ls is 299792.458 km.
- number lightYears
Generates a length-value of n lightyears. A ly is 9460730472580.8 km.
- number angstrom
Generates a length-value of n angstroms. 1 Å = 0.1 nm = 10e−10 m.
Unit Conversion[Bearbeiten]
- aLength asMeters
Returns the original length but enforces explicit printing in meters (i.e. prevents scaling prefix when printed).
- aLength asMilliMeters
Enforces explicit printing in millimeters ("mm").
- aLength asMicroMeters
Enforces explicit printing in micrometers ("µm").
- aLength asNanoMeters
Enforces explicit printing in nanometers ("nm").
- aLength asKiloMeters
Enforces explicit printing in kilometers ("km").
- aLength asAngstrom
Enforces explicit printing in angstrom ("Å").
- aLength asInches
Enforces explicit printing in inches ("in").
- aLength asFeet
Enforces explicit printing in feet ("ft").
- aLength asYards
Enforces explicit printing in yards ("yd").
- aLength asFeetAndInches
Enforces explicit printing in feet and inches (inches rounded to 4 digits).
- aLength asLandMiles
Enforces explicit printing in land miles ("mi"). One land mile is 1.609344 km.
- aLength asNauticalMiles
Enforces explicit printing in nautical miles ("NM"). One nautical mile is 1.852 km.
- aLength asLightYears
Enforces explicit printing in lightyears ("ly"). A light year is 9460730472580.8 km.
- aLength asLightSeconds
Enforces explicit printing in lightseconds ("ls"). A light second is 299792.458 km.
Angle[Bearbeiten]
Angles are measured in Radians, and the default printing is in "rad".
The following operations return an instance of angle:
Instance Creation[Bearbeiten]
- number radians
Generates an angle of n radians.
- number degrees
Generates an angle of n degrees (which prints itself as radians)
Notice that Number can also compute the raw value (as scalar number) with "degreesToRadians" and "radiansToDegrees".
Unit Conversion[Bearbeiten]
- anAngle asDegrees
Returns the same angle but enforces explicit printing in Degrees.
- anAngle asRadians
Returns the same angle but enforces explicit printing in Radians (i.e. to convert back from above degrees value).
- anAngle asArcSec
Returns the same angle but enforces explicit printing in arc seconds.
- anAngle asArcMin
Returns the same angle but enforces explicit printing in arc minutes.
- anAngle asDegreeAndMinAndSec
Returns the same angle but enforces explicit printing as d°m′s″
(eg. "90.1234 degrees asDegreeAndMinAndSec" => 90°7′24″).
Trigonometric[Bearbeiten]
- anAngle sin
Angles understand the typical trigonometric messages sin, cos, tan, cot (cotangent) and csc (cosecant).
(Eg. you can write "45 degrees sin" to get 0.707106781186547)
Temperature[Bearbeiten]
Temperature is measured in Kelvin, and the default printing is in "K".
Instance Creation[Bearbeiten]
- number kelvin
Generates an temperature-value of n Kelvin.
- number degreesCelcius
Generates an temperature-value of n degrees Celsius.
- number degreesFahrenheit
Generates an temperature-value of n degrees Fahrenheit.
- number rankine
Generates an temperature-value of n degrees Rankine.
Unit Conversion[Bearbeiten]
- aTemperature asFahrenheit
Returns the original temperature but enforces explicit printing in Fahrenheit.
- aTemperature asCelsius
Enforces explicit printing in degrees celsius.
- aTemperature asRankine
Enforces explicit printing in rankine.
Frequency[Bearbeiten]
Frequency is measured in Hertz, and the default printing is in "Hz", "kHz", "MHz" or whatever the print function chooses.
Instance Creation[Bearbeiten]
- number hertz
Generates a frequency-value of n hertz.
- number kiloHertz
Generates a frequency-value of n kilohertz.
Same asn kilo hertz
.
- number megaHertz
Generates a frequency-value of n megahertz.
Same asn mega hertz
.
- number gigaHertz
Generates a frequency-value of n gigahertz.
Same asn giga hertz
.
- Physic::Frequency noteName: aString
Converts the name of a note (in international note notation) to a frequency.
For example,Physic ::Frequency noteName: 'A4'
generates 440Hz.
- Physic::Frequency midiNr: anInteger
Converts a Midi note number (0..127) to a frequency.
For example,Physic ::Frequency midiNr: 69
generates 440Hz.
Unit Conversion[Bearbeiten]
- aFrequency asKiloHertz
Returns the original frequency but enforces explicit printing in kilohertz ("kHz").
- aFrequency asMegaHertz
Enforces explicit printing in megahertz ("MHz").
- aFrequency asGigaHertz
Enforces explicit printing in gigahertz ("GHz").
- aFrequency noteName
The name of the nearest note (equal tempered).
- aFrequency midiNr
The nearest Midi note number.
Energy[Bearbeiten]
Energy is measured in Joule, and the default printing is in "J", "kJ" or whatever the print function chooses.
Many domains have their own preferred unit to use (atom physics use electron volts, energy industry uses wattHours and the oil industry uses btu).
Instance Creation[Bearbeiten]
- number joule
Generates an energy-value of n joule.
- number kiloJoule
Generates an energy-value of n kilojoule.
Same asn kilo joule
.
- number megaJoule
Generates an energy-value of n megajoule.
Same asn mega joule
.
- number wattHours
Generates an energy-value of n wattHours.
Same asn watt * 1 hours
.
- number kiloWattHours
Generates an energy-value of n kiloWattHours.
Same asn kilo wattHours
and also the same asn kilo watt * 1 hours
.
- number megaWattHours
Generates an energy-value of n megaWattHours.
Same asn mega wattHours
and also the same asn mega watt * 1 hours
.
- number electronVolts
Generates an energy-value of n electronVolts.
- number btu
Generates an energy-value of n BTUs (British Thermal Units).
- number calories
Generates an energy-value of n calories.
- number kiloCalories
Generates an energy-value of n kcal.
Same asn kilo calories
.
Unit Converting[Bearbeiten]
- energy asElectronVolts
Present as electronVolts ("eV")
- energy asKiloWattHours
Present as kiloWattHours ("kWh")
- energy asMegaWattHours
Present as megaWattHours ("mWh")
- energy asGigaWattHours
Present as gigaWattHours ("gWh")
- energy asBTUs
Present as BTUs (British Thermal Units)
- energy asCalories
Present as calories ("cal")
- energy asKiloCalories
Present as kilo calories ("kcal")
Power[Bearbeiten]
Power is measured in Watt, and the default printing is in "W", "kW" or whatever the print function chooses. Instances of "Power" are returned eg. when multiplying an electric current by a voltage.
Instance Creation[Bearbeiten]
- number watt
Generates a power-value of n watt.
- number milliWatt
Generates a power-value of n milliWatt.
Same as "n milli watt
".
- number kiloWatt
Generates a power-value of n kiloWatt.
Same as "n kilo watt
".
- number megaWatt
Generates a power-value of n megaWatt.
Same as "n mega watt
".
- number gigaWatt
Generates a power-value of n gigaWatt.
Same as "n giga watt
".
Unit Converting[Bearbeiten]
- power asMilliWatt
Presents itself as mW
- power asKiloWatt
Presents itself as kW
- power asMegaWatt
Presents itself as mW
- power asGigaWatt
Presents itself as gW
- power asDBm
Presents itself as decibel based on milliwatt (1 mW is 0.0 dBm; 1 W is 30.0 dBm)
- power asDBW
Presents itself as decibel based on watt (1 W is 0.0 dBW; 1 kW is 30.0 dBW)
Force[Bearbeiten]
Force is measured in Newton, and by default printed as such.
Instance Creation[Bearbeiten]
- number newton
Generates a force-value of n newton.
- Physic::Force kilopond: kpNumber
Force from a given Kilopond amount. Notice that the Kilopond is no longer allowed (since 1978). So this should only be used when reading/converting old historic data.
Unit Converting[Bearbeiten]
- force asGramForce
Presents itself as gf
- force asTonForce
Presents itself as tf (metric tons of force)
- force asPoundsForce
Presents itself as lbf
Area[Bearbeiten]
Area is a derived unit based on length in meters and measured in square meter. The default printing is in "m²". Instances of "Area" are created eg. when multiplying two length values or when dividing a volume by a length.
Instance Creation[Bearbeiten]
- number squareMeter
Generates an area-value of n square meters (m²).
- number squareKiloMeter
Generates an area-value of n square kilometers (1000*1000 m²).
- number hectare
Generates an area-value of n hectares. Same asn hecto are
or 10000 m².
- number are
Generates an area-value of n ares. 1 are being 10 m².
- number squareFeet
Generates an area-value of n square feet. 1 sq ft being 0.0929 m².
- number acres
Generates an area-value of n acres. 1 acre being 4046.856 m².
Converting[Bearbeiten]
- area asHectare
Presents itself as hectare ("ha")
- area asAre
Presents itself as are (10 m²)
- area asSquareFeet
Presents itself as square feet ("m²")
- area asAcres
Presents itself as acres ("ac")
- area asSquareMiles
Presents itself as square miles ("sqm") (based on a land mile being 1609.344 m)
Volume[Bearbeiten]
Volume is a derived unit based on length in meters and measured in cubic meter. The default printing is in "m³", although the print function may choose to print in liters "l", or milli liters "ml" etc. Instances of "Volume" are created eg. when multiplying an area by a length or when cubing a length.
Instance Creation[Bearbeiten]
- number cubicMeter
Generates an volume-value of n cubic meters (1000 l).
- number liter
Generates an volume-value of n liters.
- number milliLiter
Generates a volume-value of n milliliters.
Same as "n milli liter
".
- number hectoLiter
Generates a volume-value of n hectoliters.
Same as "n hecto liter
".
- number barrel
Generates a volume of n barrels (oil volume measurement).
- number flozGB
Generates a volume of n imperial fluid ounces (0.02841 liter).
- number flozUS
Generates a volume of n US fluid ounces (0.02957 liter).
- number pintGB
Generates a volume of n imperial pints (568.26125 ml).
- number pintUS
Generates a volume of n US pints (473.176473 ml). It seems that british drinkers get more for the pint ;-)
- number quartGB
Generates a volume of n imperial quarts (1.1365 liter).
- number quartUS
Generates a volume of n US quarts (946.353 ml).
- number gallonGB
Generates a volume of n imperial gallons (4.5461 liter).
- number gallonUS
Generates a volume of n US gallons (3.7854 liter).
Converting[Bearbeiten]
- volume asCubicMeters
Presents itself as cubic meters ("mˆ3") (not as "ml" or "l")
- volume asLiters
Presents itself as liters ("l"). (not as "ml" or "mˆ3")
- volume asHectoLiters
Presents itself as hectoliters ("hl") (not as "ml", "l" or "mˆ3")
- volume asMilliLiters
Presents itself as milliliters ("ml") (not as "l" or "mˆ3")
- volume asCubicInches
Presents itself as cubic inches ("cuin")
- volume asFlozGB
Presents itself as imperial fluid ounces ("imp fl oz")
- volume asFlozUS
Presents itself as US fluid ounces ("us fl oz")
- volume asGallonsGB
Presents itself as imperial gallons ("imp ga")
- volume asGallonsUS
Presents itself as US gallons ("us ga")
Velocity (Speed)[Bearbeiten]
Velocity is a derived unit based on length in meters and measured in meters per second. The default printing is in "m/s". Instances of "Velocity" are created eg. when dividing a length by a time duration.
Instance Creation[Bearbeiten]
- number meterPerSecond
Generates a velocity of n meters per second.
- number kiloMeterPerHour
Generates a velocity of n km per hour.
- number milesPerHour
Generates a velocity of n mph.
- number knots
Generates a velocity of n nautical miles per hour.
- Physic::NatureConstants lightspeed
Speed of light in vacuum
- Physic::NatureConstants soundspeed
Speed of sound (in dry air at 20°C)
Converting[Bearbeiten]
- volume asKiloMetersPerHour
Presents itself as km/h
- volume asMilesPerHour
Presents itself as mph
- volume asKnots
Presents itself as nautical knots (kn). 1 knot being 0.514 m/s or 1.852 km/h ("1.0 knots asKiloMetersPerHour").
Acceleration[Bearbeiten]
Velocity is a derived unit based on length in meters and measured in meters per second per second. The default printing is in "m/s²". Instances of "Acceleration" are created eg. when dividing a velocity by a time duration.
Instance Creation[Bearbeiten]
- number metersPerSecondPerSecond
Generates an acceleration of n m/s².
Pressure[Bearbeiten]
Pressure is a derived unit measured in Pascal. The default printing is in "Pa". Instances of "Pressure" are created eg. when dividing a force by an area.
Instance Creation[Bearbeiten]
- number pascal
Generates a pressure value of n pascal.
- number hectoPascal
Generates a pressure value of n hectoPascal.
Same as "n hecto pascal
".
Converting[Bearbeiten]
- volume asBar
Presents itself as bar
- volume asPSI
Presents itself as psi (pounds per square inch)
- volume asAtmospheres
Presents itself as atm
Voltage[Bearbeiten]
Voltage is a derived unit measured in Volt. The default printing is in "V", "mV", "kV" as appropriate.
Instance Creation[Bearbeiten]
- number volts
Generates an electrical voltage of n volts.
- number milliVolt
Generates a voltage of n millivolt.
- number microVolt
Generates an voltage of n microvolt.
- number kiloVolt
Generates an voltage of n kilovolt.
Electric Current[Bearbeiten]
A derived unit measured in Ampere. The default printing is in "A", "mA", "kA" as appropriate. Instances of "Current" are created eg. when dividing an electric charge by a time duration.
Instance Creation[Bearbeiten]
- number ampere
Generates an electric current of n ampere.
- number milliAmpere
Generates an electric current of n milliampere.
- number microAmpere
Generates an electric current of n microampere.
Converting[Bearbeiten]
- aCap asKiloAmperes
Presents itself as "kA"
- aCap asMilliAmperes
Presents itself as "mA"
- aCap asMicroAmperes
Presents itself as "uA"
- aCap asNanoAmperes
Presents itself as "nA"
- aCap asPicoAmperes
Presents itself as "pA"
Electric Resistance[Bearbeiten]
A derived unit measured in Ohm. The default printing is in "Ω", "kΩ", "MΩ" as appropriate.
Instance Creation[Bearbeiten]
- number ohm
Generates an electric resistance of n ohm.
- number kiloOhm
Generates an electric current of n kiloOhm.
- number megaOhm
Generates an electric current of n megaOhm.
Electric Capacitance[Bearbeiten]
A derived unit measured in Farad. The default printing is in "F", "uF", "nF", "pF" as appropriate.
Instance Creation[Bearbeiten]
- number farad
Generates an electric capacitance of n farad.
- number microFarad
Generates an electric capacitance of n microfarad.
- number nanoFarad
Generates an electric capacitance of n nanofarad.
- number picoFarad
Generates an electric capacitance of n picofarad.
Converting[Bearbeiten]
- aCap asMicroFarads
Presents itself as "uF"
- aCap asNanoFarads
Presents itself as "nF"
- aCap asPicoFarads
Presents itself as "pF"
Electric Charge[Bearbeiten]
A unit measured in Coulomb. The default printing is in "C". Instances of "Charge" are created eg. when multiplying an electric current by a time duration.
Instance Creation[Bearbeiten]
- number coulomb
Generates an electric charge of n coulomb.
Converting[Bearbeiten]
- aCharge asAmpereSeconds
Presents itself as "As" (which is also a coulomb, but "As" might be preferred in some domains)
- aCharge asAmpereHours
Presents itself as "Ah"
Inductance[Bearbeiten]
A unit measured in Henry (H).
Instance Creation[Bearbeiten]
- number henry
Generates an inductance of n henry.
LuminousIntensity[Bearbeiten]
A unit measured in Candela (cd).
Instance Creation[Bearbeiten]
- number candela
Generates a luminousIntensity of n candela.
Luminance[Bearbeiten]
A unit measured in Lux (lx).
MagneticFlux[Bearbeiten]
A unit measured in Weber (Wb).
MagneticFluxDensity[Bearbeiten]
A unit measured in Tesla (T).
Mass Density[Bearbeiten]
A unit measured in kg/m³. Instances are created eg. when dividing a mass by a volume.
Converting[Bearbeiten]
- massDensity asGramPerCubicCentimeter
Presents itself as g/cm³
Defining Additional Unit Converters[Bearbeiten]
You can define additional unit converters as ConvertedUnit as follows:
myUnit := Physic::ConvertedUnit name:name baseUnit:baseUnit unitString:unitString unitValueBlock:unitValueBlock baseUnitValueBlock:baseUnitValueBlock
Where baseUnit is the underlying base (SI) unit, unitString is the string used when printing, unitValueBlock is a Smalltalk block to compute the unit value from a base unit value and baseUnitValueBlock is a Smalltalk block to compute the base unit value from the unit value.
Example: Cubic Inch Unit[Bearbeiten]
For example, to get volumes printed as cubic inches, you could define 1):
cI := Physic::ConvertedUnit name:'cubicInches' baseUnit:(Physic::Volume) unitString:'in³' unitValueBlock:[:cubicMeters | cubicMeters * 61023.7440947323] baseUnitValueBlock:[:cubicInches| cubicInches / 61023.7440947323]
i.e. to convert from base-units, which are cubic meters, into the converted cubic inches, we have to multiply by 61023.7440947323. And vice versa, we have to divide. 61023.7440947323 is the number of cubic inches per cubic meter.
Then create a new physical value for your volume with:
cI amount:volumeInCubicMeters
Example: Gummy Bear Unit[Bearbeiten]
Or, to present a mass in units of gummy-bears, assuming one bear weighs 1.1g 2):,
bearUnit := Physic::ConvertedUnit name:'Haribo-Bears' baseUnit:(Physic::Mass) unitString:'bears' unitValueBlock:[:kiloGram| kiloGram * 1000 / 1.1] baseUnitValueBlock:[:bears| bears * 1.1 / 1000]
and then take a 150g bag of bears and ask it to print itself on an output stream:
bagOfBears := bearUnit amount:0.150. bagOfBears printOn:Transcript
gives:
=> "136.363636363636 bears"
Notice, that bearUnit ("Haribo") is still a unit of mass; we can add another kilogram to those bears:
bagOfBears + 1 kilo gram
and get more bears:
=> 1045.45454545455 bears
You can also convert any mass into gummy-bears:
(1 kiloGram as:bearUnit) floor
gives:
=> 909.0 bears
Notes:
1) this is only an example; you actually don't need that, as volumes already support conversion to cubicInches (see asCubicInches below)
2) the author does not know what the actual mass of a gummy bear is ;-)
Arithmetic[Bearbeiten]
Arithmetic on physical values will generate an appropriate physical value with its own unit. Eg., when multiplying a velocity by a time, you will get a distance, or when dividing a distance by a time, you will get a velocity.
The following lists some of the possible results. Be aware that the units are ignorant of any relativistic effects. They compute their values according to classical Newtonian mechanics.
Velocity Arithmetic[Bearbeiten]
distance = velocity * time
3 meterPerSecond => 3 m/s 1 meterPerSecond * 10 seconds => 10 m 10 kiloMetersPerHour * 30 minutes => 5000 m 30 meter / 2 seconds => 15 m/s 10 meter / 1 seconds * 20 seconds => 20 m
Acceleration Arithmetic[Bearbeiten]
speed = acceleration * time
1 meterPerSecondPerSecond * 10 seconds => 10 m/s (1 meterPerSecondPerSecond distanceAfter:1 hours) => 6480.0 km 1 meterPerSecond / 10 seconds => 0.1 m/s² (9.81 meter / 1 seconds squared) * 1 hours => 70632 m/s
Mass Arithmetic[Bearbeiten]
force = mass * acceleration
1 kiloGram * 1 meterPerSecondPerSecond => 1 N 1 kilo gram * 1 meter / 1 seconds / 1 seconds => 1 N 1 kilo gram * 100 centi meter / 1 seconds squared => 1 N 1 newton / 2 kiloGram => (1/2) m/s²
Electric Arithmetic[Bearbeiten]
current = voltage / resistance
charge = voltage * capacitance
charge = current * time
10 volt / 220 ohm => 45.45 mA 150 ohm * 20 milliAmpere => 3 V 0.5 ampere * 0.5 seconds => 0.25 C 100.0 micro farad * 100 volt => 0.01 C 10.0 micro farad * 100 ohm => 1.0 ms (the RC time constant) 100 pico farad * 5 volt / 10 milli ampere => 50ns
Energy & Power Arithmetic[Bearbeiten]
10 ampere * 220 volt => 2200 W 10 ampere * 220 volt * 10 hours => 79.2 MJ 10 kiloWatt * 10 hours => 360.0 MJ (10 kiloWatt * 10 hours ) asKiloWattHours => 100 kWh
Math Functions and Trigonometric[Bearbeiten]
Angles respond to trigonometric operations:
45 degrees sin => 0.707106781186547 Float pi radian cos => -1.0
If useful, square and cubic root can be computed:
25 squareFeet sqrt => 0.3048 m 10 liter cbrt => 0.2154 m
Rounding & Truncating[Bearbeiten]
Rounding and truncation operations are provided which generate a unit with the amount processed like the corresponding number operations:
1.0 meter floor => 1 m 1.1 meter floor => 1 m 1.7 meter floor => 1 m 1.0 meter ceiling => 1 m 1.1 meter ceiling => 2 m 1.7 meter ceiling => 2 m 1.0 meter rounded => 1 m 1.1 meter rounded => 1 m 1.7 meter rounded => 2 m 1.15 meter roundTo:0.1 => 1.1 m 1.15 meter roundTo:0.2 => 1.2 m 1.15 meter roundTo:0.5 => 1 m 1.04 meter roundTo:0.2 => 1 m 1.1 meter roundTo:0.2 => 1.2 m 2 meter negated => -2 meter (4/3) meter roundedToScale:0 => 1 m (4/3) meter roundedToScale:1 => 1.3 m (4/3) meter roundedToScale:2 => 1.33 m (4/3) meter roundedToScale:3 => 1.333 m (5/3) meter roundedToScale => 1.67 m (5/3) meter roundedToScale:0 => 2 m (5/3) meter roundedToScale:1 => 1.7 m (5/3) meter roundedToScale:2 => 1.67 m (5/3) meter roundedToScale:3 => 1.667 m
Be careful with roundedToScale: it will round the unit (which in the above case is meter). If the value is small (i.e. in the cm range), rounding to scale 2 will round to 1/100 meter, which might later print strange unexpected values. Thus it is best to convert the result into a desired range (i.e. asCentimeter) and round this: eg:
15.012 centiMeter => 0.15012 m 15.0120 centiMeter roundedToScale:2 => 0.15 m 15.0120 centiMeter asCentimeters roundedToScale:2 => 15.01 cm
Formula Evaluation[Bearbeiten]
Formulae can be parsed and further processed by use of the Physic::Parser class.
Physic::Parser
parse: aString
generates a parse tree for further processing
Physic::Parser
evaluate: aString
parses and evaluates
Generated parse trees can be further processed with:
- aParseTree value
evaluates the tree
- aParseTree simplify
simplifies a parsed formula (if possible)
- aParseTree derivate
generates a derivate
Formula Examples[Bearbeiten]
(Physic::Parser parse:'a*x^2 + b*x + c') derivate -> 2·a·x + b (Physic::Parser parse:'sin(a*x) + cos(b*x)') derivate -> cos(a·x)·a - sin(b·x)·b
Providing additional Formulas[Bearbeiten]
The framework's knowledge database about units is defined by a set of formulas, from which result units are determined, when arithmetic operations are performed on physical values.
This set of default formulas can be retrieved via "PhysicalUnit formulaStrings".
You can add more knowledge by:
PhysicalUnit addFormula: formulaString
As a concrete example, the Momentum (which is Energy * Time) is predefined via:
PhysicalUnit addFormula:'Momentum = Energy * Time'
the names in the formula must correspond to the unit names; if new units are to be made well known, it must be defined via:
PhysicalUnit addKnownUnit:aUnit
or
PhysicalUnit addKnownUnit:aUnit as:nameInFormula
Nature Constants[Bearbeiten]
The following constants are known to the parser and can be used in formula/equations:
Fundamental Constants[Bearbeiten]
pi e BoltzmannConstant AvogadroConstant ElectronCharge PlanckConstant PlanckTime PlanckMass LightSpeed GravitationalConstant
Elements[Bearbeiten]
atom => database with facts about atoms atom[X], for X in {'H','He','Na','Li','C','N','O','Au',...}.
provides data for 'name', 'symbol', 'atomNr', 'atomWeight', 'meltingTemperature', 'boilingTemperature', 'protons', 'neutrons', 'density'.
For example:
(Physic::NatureConstants atom)['He']['atomWeight'] => 4.002602 amu (Physic::NatureConstants atom)['Li']['density'] => 534.0 kg/m³
The builtin database is incomplete; you may want to fill in missing data in an initialization action, as described below.
Astronomic Data[Bearbeiten]
astronomicalObjects[X], for X in {'earth', 'moon', 'sun', 'mercure', 'venus', 'mars', 'jupiter', 'saturn', 'neptune', 'uranus', 'pluto' }
provides planetary data ['mass'], ['radiusMean'], ['volume'], ['aphelion'], ['perihelion'].
Eg. planet['venus']['mass']
(Physic::NatureConstants astronomicalObjects)['venus']['mass']
also:
mass[X], for X in planet-names volume[X], for X in planet-names radius[X], for X in planet-names
DISTANCE_SUN_EARTH DISTANCE_EARTH_MOON AstronomicalUnit EarthGravity earth, moon, sun, mercure, venus, mars, jupiter, saturn, uranus, neptune, pluto
Earth[Bearbeiten]
mass[X], for X in {'earthWater', 'earthAtmosphere'} surface[X], for X in {'earthLand' 'earthWater'}
Filling the Facts Database[Bearbeiten]
The database as deployed obviously cannot provide any possible useful value for you particular application. The current set is provided for examples and only contains knowledge which is often used in physics, some chemistry and mechanical applications.
If you expect more builtin data, please let us know. If you find inexact values (or wrong values due to typing errors), let us know.
In any case, you can yourself fill the database with both missing, inexact or wrong values:
Physic::NatureConstants constants[name] := newValue
or (the equivalent):
Physic::NatureConstants constants at:name put:newValue
For example, to add data for an atom, you could write:
goldInfo := (Physic::NatureConstants constants)['atom']['AU']. goldInfo['meltingTemperature'] := 1337.33 kelvin.
You can also add completely new domain specific data:
woodData := Dictionary new. woodData['walnut'] = #{ density: 650 kiloGram / 1 cubicMeter }. woodData['mahogany'] = #{ density: 600 kiloGram / 1 cubicMeter }. woodData['maple'] = #{ density: 700 kiloGram / 1 cubicMeter }. woodData['oak'] = #{ density: 770 kiloGram / 1 cubicMeter }. woodData['rosewood'] = #{ density: 840 kiloGram / 1 cubicMeter }. woodData['cherry'] = #{ density: 7400 kiloGram / 1 cubicMeter }. woodData['balsa'] = #{ density: 120 kiloGram / 1 cubicMeter }. Physic::NatureConstants constants['wood'] := woodData.
then use in your code:
Physic::NatureConstants['wood']['çherry']['density']
(these numbers are just examples; the actual densities vary much and also depend on dryness and other factors)
Examples Involving Constants[Bearbeiten]
In Smalltalk (accessing the constants directly):
Physic::NatureConstants['speed']['sound'] Physic::NatureConstants['planets']['venus'] Physic::NatureConstants['planets']['mars']['mass']
In JavaScript:
Physic::NatureConstants['speed']['sound']
In Smalltalk (using the Math language parser):
Physic::Parser evaluate:'1 kg * LightSpeedˆ2'. Physic::Parser evaluate:'1 kg * LightSpeed²' Physic::Parser evaluate:'mass[sun] * mass[earth] / earth[perihelion]ˆ2'.
In Math language:
1 kg * LightSpeedˆ2 GraviationalConstant * mass[sun] * mass[earth] / earth[perihelion]²
Equation Solving[Bearbeiten]
The solver can solve simple equations:
equation := Physic::Parser parse:'a = 5*b + c'. equation solveFor:'b' => b = (a - c) / 5
(actually, it will give "b = (-1/5)·(c - a)", which is cheaper to compute)
For example, from the wellknown Formula "U = R * I",
equation := Physic::Parser parse:'U = R * I'.
we can derive:
equation2 := equation solveFor:'R'.
and get "R = U/I".
Of which the right side:
formulaForR := equation2 rightSide => U/I
Applying this formulaForR to concrete values:
formulaForR valueIn:{ 'U' -> 5 volt . 'I' -> 20 milliAmpere } => 250 Ω
Measured Physical Values[Bearbeiten]
You can combine physical values and measurement values to keep track of errors in computations.
Example:
Assuming, that your cheap 10% accurate voltmeter measured 10 volts, this could be written as:
u := (10 volt ±% 10).
and if that voltage was measured across a cheap 100 ohm resistor with 5% precision,
r := (100.0 ohm ±% 5).
the current will be:
i := u / r.
which is:
(MeasurementValue value:100.0 minValue:(85.714285714285708) maxValue:(115.78947368421052)) mA
and its min/max/expected values can be extracted with:
i minValue => 85.7142857142857 mA i maxValue => 115.789473684211 mA i expectedValue => 100 mA
or nicer:
i minValue asMilliAmperes roundedToScale:2 => 85.71 mA i maxValue asMilliAmperes roundedToScale:2 => 115.79 mA i expectedValue asMilliAmperes roundedToScale:2 => 100 mA
Notice: currently, you cannot take the plain minValue/maxValue and round them, as these are kept in baseUnits internally, which would round to 1/100 ampere instead of 1/100 milliampere. Therefore, the values are first forced into milliAmperes so that the rounding is what we want.
Physical Values and Numeric Precision[Bearbeiten]
Physical values will use the underlying number type when computing new values. For example,
10 volt / 3 ampere -> (10/3) ohm
i.e. a fractional Ohm value, whereas:
10.0 volt / 3 ampere -> 3.33333 ohm
i.e. a float value.
It is usually a good idea to start with float values, and scale to the desired precision output when printing. Please refer to the "Numeric Limits" document for more details on number types.
Physical Values in Activity Diagrams[Bearbeiten]
Unfortunately, the arithmetic actions in the standard library were defined with pin types being "Number
", instead of the more general "ArithmeticValue
" (of which PhysicalValues inherit). Thus, they will not accept physical values if type checking is enabled on the pin values (although the underlying primitive code would handle those types).
We therefore provide a separate PhysicalValues library, with redefined arithmetic actions. Please use those when dealing with physical values (instead of "forcing" types or disabling type checks).
Freeze values can be given either using the above listed instance creation messages on number (eg. "10 meters
" or "1 kilo joule
") or by using a unit suffix, possibly with an appreciated SI prefix, as in "10 kV
" or "10 mA
".
Physical Values in Elementary Code[Bearbeiten]
See examples below.
Math Language Workspace[Bearbeiten]
You can switch the workspace (Notepad) window to accept math language syntax (instead of Smalltalk or JavaScript).
For this, open a Notepad via "Extras" - "Tools" - "Notepad'", and choose "Math/Physic" in its "Workspace" menu1).
You can now enter math language expressions, such as:
x := 5 sin(xˆ2 + 3) => 1.35452894153935
or
deriv ( sin(xˆ2 + 5x), x ) => (2·x + 5)·cos(x² + 5·x)
1) Make sure that "Autodefine as Workspace Variable" is checked in the "Workspace" - "Autodefine" menu (otherwise assigned variables such as "x" above will only be known within one doIt).
Examples[Bearbeiten]
The following code snippets are plain Smalltalk code + the printed representation (as for example found in a report).
For JavaScript, write "n.X()" instead of "n X" (eg. "1.kilogram() + 10.0.gram()
" instead of "1 kiloGram + 10.0 gram
".
The following shows the printed output of typical Smalltalk expressions:
Length Examples:[Bearbeiten]
(1/4) inches | => | 6.25 mm |
10 milliMeter asInches | => | 0.3937 in |
10 milli meter asInches | => | 0.3937 in |
10 feet | => | 3.048 m |
1.8 meter asFeet | => | 5.905 ft |
10 miles | => | 16.09 km |
10 nauticalMiles | => | 18.52 km |
1 parsec | => | 3.26156377716705 ly |
10 kiloMeters asMeters | => | 10000 m |
1 micro inch | => | 25.4 nm |
1.80 meter asFeetAndInches | => | 5′10.866 |
1 yards | => | 0.9144 m |
Mass Examples:[Bearbeiten]
1 kiloGram + 10.0 gram | => | 1.01 kg |
(1 kiloGram + 10 gram) asGrams | => | 1010 g |
10 gram | => | 10 g |
10 gram asKiloGrams | => | (1/100) kg |
10.0 gram asKiloGrams | => | 0.01 kg |
10 gram asMilliGrams | => | 10000 mg |
1 microGram | => | 1 µg |
1 micro gram | => | 1 µg |
10000 gram | => | 10 kg |
1 pound | => | 453.59237 g |
1 pound asKiloGrams | => | 0.45359237 kg |
1 pound asPounds | => | 1.0 lb |
1 kiloGram asPounds | => | 2.20462262184878 lb |
Temperature Examples:[Bearbeiten]
0 degreesCelsius | => | 273.16 K |
0 degreesCelsius asFahrenheit | => | 32.018 °F |
40 degreesFahrenheit | => | 277.59 K |
60 degreesFahrenheit asCelsius | => | 15.556 °C |
40 degreesFahrenheit asKelvin | => | 277.59 K |
10 kelvin | => | 10 K |
100 rankine | => | 55.556 K |
100 rankine asRankine | => | 100.0 °R |
Energy Examples:[Bearbeiten]
1 joule asElectronVolts | => | 6.24150912550149E+18 eV |
1 joule asCalories | => | 0.239005736137667 cal |
1 joule asBTUs | => | 0.000947817 BTU |
1.0 joule asKiloWattHours | => | 2.77777777777778E-07 kWh |
10 electronVolts | => | 1.6021766208E-18 J |
1 mega electronVolts asJoules | => | 1.602176634E-13 J |
1000 joule asKiloWattHours | => | 0.000278 kWh |
1000.0 kiloJoule asKiloWattHours | => | 0.2778 kWh |
Electricity Examples:[Bearbeiten]
1 coulomb asAmpereHours | => | 0.000277 Ah |
1.1 volt / 10 kilo ohm | => | 110.0 µA |
100 micro farad * 10.0 volt | => | 0.001 C |
100 ohm * 0.1 micro farad | => | 10.0 µs |
20 milli ampere * 10 seconds | => | XXX C |
Volume Examples:[Bearbeiten]
1000 liter | => | 1 m³ |
1000 liter asLiters | => | 1000 l |
1000 liter asHectoLiters | => | 10 hl |
1000 liter asCubicInches | => | 61023.7440947323 cuin |
100.0 liter asCubicInches | => | 6102.37440947323 cuin |
100.0 deci liter asCubicInches | => | 610.237440947323 cuin |
1 liter asCubicInches | => | 61.0237440947323 cuin |
1 deci liter asCubicInches | => | 6.10237440947323 cuin |
1 milli liter asCubicInches | => | 0.0610237440947323 cuin |
1 inch cubed | => | 16.387064 ml |
1 inch cubed asLiters | => | 0.016387064 l |
1 inch cubed asCubicInches | => | 1.0 cuin |
1 inch cubed asCubicInches unitString | => | 'cuin' |
1 inch cubed asCubicInches unitAmount | => | 1.0 |
1 inch cubed asCubicInches unitStringSI | => | 'm³' |
1 inch cubed asCubicInches amount | => | 1.6387064E-05 |
Angle Examples:[Bearbeiten]
10 degrees | => | 0.174533 rad |
0.2 radians | => | 0.2 rad |
180 degrees | => | 3.14159265358979 rad |
180 degrees asDegrees | => | 180.0 ° |
180 degrees asDegrees asRadians | => | 3.14159265358979 rad |
gonUnit := (Physic::PhysicalUnit angle gon) | => | Gon (the unit, not a value) |
gonUnit unitAmount:100 | => | 100 gon |
(gonUnit unitAmount:100) asDegrees | => | 90 ° |
270 degrees + 91 degrees = 361 degrees | => | true |
Bytes Examples:[Bearbeiten]
1 kilo byte | => | 1000 byte |
1 kibi byte | => | 1024 byte |
100 kilo byte asKibiBytes rounded | => | 98 kiB |
1 kilo byte / 1 seconds | => | 1000 B/s |
1 kilo byte / 1 seconds * 5 minutes | => | 300 kB |