Expressions/es: Difference between revisions

From FreeCAD Documentation
(Created page with "==== Funciones trigonométricas ====")
(Updating to match new version of source page)
 
(77 intermediate revisions by 2 users not shown)
Line 2: Line 2:
{{TOCright}}
{{TOCright}}


<span id="Overview"></span>
==Resumen==
==Resumen==


Es posible definir propiedades utilizando expresiones matemáticas. En la interfaz gráfica de usuario, los cuadros de giro o campos de entrada que están vinculados a las propiedades contienen un icono azul [[Image:Bound-expression.svg|24px]]. Haciendo clic en el icono o escribiendo el signo igual {{KEY|&#61;}} aparece el editor de expresiones para esa propiedad en particular.
Es posible definir propiedades utilizando expresiones matemáticas. En la interfaz gráfica de usuario, los cuadros de giro o campos de entrada que están vinculados a las propiedades contienen un icono azul [[Image:Bound-expression.svg|24px]]. Haciendo clic en el icono o escribiendo el signo igual {{KEY|&#61;}} aparece el editor de expresiones para esa propiedad en particular.


Es una expresión matemática que sigue la notación de los operadores y funciones matemáticas estándar, como se describe a continuación. Además, la expresión puede hacer referencia a otras propiedades, y también utilizar condicionales. Los números en una expresión pueden tener una unidad opcional adjunta.
Es una expresión matemática que usa la notación de los [[#Supported_operators|operadores]], [[#Supported_functions|funciones]] y [[#Supported_constants|constantes predefinidas]] matemáticas estándar como se describe a continuación. Además, la expresión puede hacer referencia a otras propiedades de objetos, y también utilizar [[#Conditional_expressions|condicionales]]. Los números en una expresión pueden tener una [[#Units|unidad]] opcional adjunta.


Los número pueden usar ya sea una coma {{incode|,}} o un punto decimal {{incode|.}} para separar los dígitos enteros de los decimales.
Los números pueden usar ya sea una coma {{incode|,}} o un punto decimal {{incode|.}} para separar los dígitos enteros de los decimales. Cuando se usa el marcador decimal, ''debe'' ser seguido por al menos un dígito. Por lo tanto, las expresiones {{incode | 1.+2.}} y {{incode | 1,+2,}} son inválidas, pero {{incode | 1.0+2.0}} y {{incode | 1,0+2,0}} son válidas.
Cuando se usa el marcador decimal, "debe" ser seguido por al menos un dígito. Por lo tanto, las expresiones {{incode | 1.+2.}} y {{incode | 1,+2,}} son inválidas, pero {{incode | 1.0+2.0}} y {{incode | 1,0+2,0}} son válidas.


Los operadores y las funciones son conscientes de la unidad y requieren combinaciones válidas de unidades, si se suministran. Por ejemplo, {{incode | 2mm+4mm}} es una expresión válida, mientras que {{incode | 2mm+4}} no lo es (la razón es que una expresión como {{incode | 1in+4}} probablemente será interpretada como {{Incode | 1in+4in}} por los humanos, pero todas las unidades se convierten al sistema métrico internamente, y el sistema no puede adivinar esto). Estas [[#Unidades|unidades]] son reconocidas actualmente.
Los operadores y las funciones son conscientes de la unidad y requieren combinaciones válidas de unidades, si se suministran. Por ejemplo, {{incode | 2mm+4mm}} es una expresión válida, mientras que {{incode | 2mm+4}} no lo es. Esto también se aplica a las referencias a propiedades de objetos que tienen unidades, como las propiedades de longitud. Por lo tanto, {{incode|Pad001.Length + 1}} es inválido ya que agrega un número puro a una propiedad con unidades de longitud, se requiere {{incode|Pad001.Length + 1mm}}.


Algunos errores relacionados con las unidades pueden parecer poco intuitivos, ya que las expresiones se rechazan o producen resultados que no coinciden con las unidades de la propiedad que se establece. Aquí hay unos ejemplos:
Puedes usar [[#Constantes_soportadas|constantes predefinidas]] y [[#Funciones_soportadas|funciones]].


{{incode|1/2mm}} no se interpreta como medio milímetro sino como {{incode|1/(2mm)}}, lo que da como resultado: {{incode|0.5 mm^-1}}.

{{incode|sqrt(2)mm}} no es válido porque la llamada a la función no es un número. Esto debe ingresarse como {{incode|sqrt(2) * 1mm}}.

<span id="Function_arguments"></span>
===Argumentos de la función===
===Argumentos de la función===


Line 21: Line 26:
Los argumentos pueden incluir referencias a las celdas en una hoja de cálculo. Una referencia de celda consiste en la letra mayúscula de fila de la celda seguida de su número de columna, por ejemplo {{incode | A1}}. También se puede hacer referencia a una celda utilizando el alias de la celda, por ejemplo, {{incode|Spreadsheet.MyPartWidth}}.
Los argumentos pueden incluir referencias a las celdas en una hoja de cálculo. Una referencia de celda consiste en la letra mayúscula de fila de la celda seguida de su número de columna, por ejemplo {{incode | A1}}. También se puede hacer referencia a una celda utilizando el alias de la celda, por ejemplo, {{incode|Spreadsheet.MyPartWidth}}.


<span id="Referencing_objects"></span>
===Referencia de objetos===
===Referencia de objetos===


Puede hacer referencia a un objeto por su {{PropertyData | Name}} o por su {{PropertyData | Label}}. En el caso de un {{PropertyData | Label}}, debe estar encerrado en doble símbolos {{incode | <<}} y {{incode | >>}}, como {{incode | <<Label>>}}.
Como ya se mostró arribam puede hacer referencia a un objeto por su {{PropertyData | Name}}. Pero también puedes usar su {{PropertyData | Label}}. En el caso de un {{PropertyData | Label}}, debe estar encerrado en doble símbolos {{incode | <<}} y {{incode | >>}}, como {{incode | <<Label>>}}.


Puede referenciar cualquier propiedad de un objeto. Por ejemplo, para referenciar la altura de un Cilindro puede usar {{incode|Cylinder.Height}} o {{incode|<<Long_name_of_cylinder>>.Height}}. Para referenciar al objeto mismo use la pseudo propiedad {{incode|_self}}. Por ejemplo, puede usar {{incode|Cylinder._self}} o {{incode|<<Label_of_cylinder>>._self}}.
Puede referenciar cualquier propiedad de un objeto. Por ejemplo, para referenciar la altura de un Cilindro puede usar {{incode|Cylinder.Height}} o {{incode|<<Label_of_cylinder>>.Height}}.

Para referenciar una lista de objetos use {{incode|<<object_label>>.list[list_index]}} or {{incode|object_name.list[list_index]}}. Si quiere por ejemplo referenciar una restricción de un croquis use {{incode|<<MySketch>>.Constraints[16]}}. Si está en el mismo croquis puede omitir su nombre y solo usar {{incode|Constraints[16]}}.<br/>
'''Nota:''' El índice inicia en 0, por lo que la restricción 17 tiene el índice 16.


Para más información de como referenciar objetos, vea [[#Referencia_a_los_datos_CAD|Referencia a los datos CAD]].
Para más información de como referenciar objetos, vea [[#Referencia_a_los_datos_CAD|Referencia a los datos CAD]].
{{Top}}
{{Top}}
<span id="Supported_constants"></span>
== Constantes soportadas ==
== Constantes soportadas ==


Line 47: Line 51:
|}
|}
{{Top}}
{{Top}}
<span id="Supported_operators"></span>
== Operadores soportados ==
== Operadores soportados ==


Line 74: Line 79:
|}
|}
{{Top}}
{{Top}}
<span id="Supported_functions"></span>
== Funciones soportadas ==
== Funciones soportadas ==


<span id="General_mathematical_functions"></span>
=== Funciones matemáticas generales ===
=== Funciones matemáticas generales ===


Las siguientes funciones matemáticas son soportadas:
Las siguientes funciones matemáticas son soportadas:


<span id="Trigonometric_functions"></span>
==== Funciones trigonométricas ====
==== Funciones trigonométricas ====


[https://en.wikipedia.org/wiki/Trigonometric_functions Trigonometric functions] use degree as their default unit. For radian measure, add {{incode|rad}} following the <em>first</em> value in an expression. So e.g. {{incode|cos(45)}} is the same as {{incode|cos(pi rad / 4)}}. Expressions in degrees can use either {{incode|deg}} or {{incode|°}}, e.g. {{incode|360deg - atan2(3; 4)}} or {{incode|360&deg; - atan2(3; 4)}}. If an expression is without units and needs to be converted to degrees or radians for compatibility, multiply by {{incode|1&nbsp;deg}}, {{incode|1&nbsp;°}} or {{incode|1&nbsp;rad}} as appropriate, e.g. {{incode|(360 - X) * 1deg}}; {{incode|(360 - X) * 1°}}; {{incode|(0.5 + pi / 2) * 1rad}}.
Las [https://es.wikipedia.org/wiki/Funci%C3%B3n_trigonom%C3%A9trica Funciones trigonométricas] utilizan el grado sexagesimal como unidad predeterminada. Para radianes, agregue {{incode|rad}} después del <em>primer</em> valor de una expresión. Entonces, por ejemplo, {{incode|cos(45)}} es lo mismo que {{incode|cos(pi rad / 4)}}. Las expresiones en grados pueden usar {{incode|deg}} o {{incode|°}}, por ejemplo, {{incode|360deg - atan2(3; 4)}} o {{incode|360&deg; - atan2(3; 4)}}. Si una expresión no tiene unidades y debe convertirse a grados o radianes para garantizar la compatibilidad, multiplíquela por {{incode|1deg}}, {{incode|1°}} o {{incode|1rad}} como apropiado, por ejemplo, {{incode|(360 - X) * 1deg}}; {{incode|(360 - X) * 1°}}; {{incode|(0,5 + pi / 2) * 1rad}}.


{| class="wikitable"
{| class="wikitable"
!style="width: 15%;"|Function
!style="width: 15%;"|Function
!style="width: 55%;"|Description
!style="width: 55%;"|Description
!style="width: 30%;"|Value range
!style="width: 30%;"|Input range
|-
|-
| acos(x)
| {{incode|acos(x)}}
| [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties Arc cosine]
| [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties Arc cosine]
| -1 <= x <= 1
| -1 <= x <= 1
|-
|-
| asin(x)
| {{incode|asin(x)}}
| [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties Arc sine]
| [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties Arc sine]
| -1 <= x <= 1
| -1 <= x <= 1
|-
|-
| atan(x)
| {{incode|atan(x)}}
| [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties Arc tangent]
| [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties Arc tangent], return value in the range -90° < value < 90°
| all
| all
|-
|-
| atan2(x; y)
| {{incode|atan2(y; x)}}
| [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties Arc tangent] of ''x/y''
| [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties Arc tangent] of ''y/x'' accounting for quadrant, return value in the range -180° < value <= 180°
| all, except y = 0
| all, the invalid input x = y = 0 returns 0
|-
|-
| cos(x)
| {{incode|cos(x)}}
| [https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions Cosine]
| [https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions Cosine]
| all
| all
|-
|-
| cosh(x)
| {{incode|cosh(x)}}
| [https://en.wikipedia.org/wiki/Hyperbolic_function#Trigonometric_definitions Hyperbolic cosine]
| [https://en.wikipedia.org/wiki/Hyperbolic_function#Trigonometric_definitions Hyperbolic cosine]
| all
| all
|-
|-
| sin(x)
| {{incode|sin(x)}}
| [https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions Sine]
| [https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions Sine]
| all
| all
|-
|-
| sinh(x)
| {{incode|sinh(x)}}
| [https://en.wikipedia.org/wiki/Hyperbolic_function#Trigonometric_definitions Hyperbolic sine]
| [https://en.wikipedia.org/wiki/Hyperbolic_function#Trigonometric_definitions Hyperbolic sine]
| all
| all
|-
|-
| tan(x)
| {{incode|tan(x)}}
| [https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions Tangent]
| [https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions Tangent]
| all, except x = n*90 with n = uneven integer
| all, except x = n*90 with n = odd integer
|-
|-
| tanh(x)
| {{incode|tanh(x)}}
| [https://en.wikipedia.org/wiki/Hyperbolic_function#Trigonometric_definitions Hyperbolic tangent]
| [https://en.wikipedia.org/wiki/Hyperbolic_function#Trigonometric_definitions Hyperbolic tangent]
| all
| all
|-
|-
| hypot(x; y)
| {{incode|hypot(x; y)}}
| [https://en.wikipedia.org/wiki/Pythagorean_addition Pythagorean addition] ('''hypot'''enuse). E.g. hypot(4; 3) = 5.
| [https://en.wikipedia.org/wiki/Pythagorean_addition Pythagorean addition] ('''hypot'''enuse), e.g. hypot(4; 3) = 5
| x and y > 0
| x and y >= 0
|-
|-
| cath(x; y)
| {{incode|cath(x; y)}}
| Given hypotenuse, and one side, returns other side of triangle. E.g. cath(5; 3) = 4.
| Given hypotenuse, and one side, returns other side of triangle, e.g. cath(5; 3) = 4
| x and y > 0, x >= y
| x >= y >= 0
|}
|}


<span id="Exponential_and_logarithmic_functions"></span>
==== Exponential and logarithmic functions ====
==== Funciones exponenciales y logarítmicas ====


{| class="wikitable"
{| class="wikitable"
!style="width: 33%;"|Function
!style="width: 33%;"|Function
!style="width: 33%;"|Description
!style="width: 33%;"|Description
!style="width: 33%;"|Value range
!style="width: 33%;"|Input range
|-
|-
| exp(x)
| {{incode|exp(x)}}
| [https://en.wikipedia.org/wiki/Exponential_function#Formal_definition Exponential function]
| [https://en.wikipedia.org/wiki/Exponential_function#Formal_definition Exponential function]
| all
| all
|-
|-
| log(x)
| {{incode|log(x)}}
| [https://en.wikipedia.org/wiki/Natural_logarithm Natural logarithm]
| [https://en.wikipedia.org/wiki/Natural_logarithm Natural logarithm]
| x > 0
| x > 0
|-
|-
| log10(x)
| {{incode|log10(x)}}
| [https://en.wikipedia.org/wiki/Common_logarithm Common logarithm]
| [https://en.wikipedia.org/wiki/Common_logarithm Common logarithm]
| x > 0
| x > 0
|-
|-
| pow(x; y)
| {{incode|pow(x; y)}}
| [https://en.wikipedia.org/wiki/Exponentiation Exponentiation]
| [https://en.wikipedia.org/wiki/Exponentiation Exponentiation]
| all
| all
|-
|-
| sqrt(x)
| {{incode|sqrt(x)}}
| [https://en.wikipedia.org/wiki/Square_root Square root]
| [https://en.wikipedia.org/wiki/Square_root Square root]
| x >= 0
| x >= 0
|-
| {{incode|cbrt(x)}} {{Version|0.21}}
| [https://en.wikipedia.org/wiki/Cube_root Cubic root]
| all
|}
|}


<span id="Rounding,_truncation_and_remainder_functions"></span>
==== Rounding, truncation and remainder functions ====
==== Funciones de redondeo, truncamiento y resto. ====


{| class="wikitable"
{| class="wikitable"
!style="width: 20%;"|Function
!style="width: 20%;"|Function
!style="width: 55%;"|Description
!style="width: 55%;"|Description
!style="width: 25%;"|Value range
!style="width: 25%;"|Input range
|-
|-
| abs(x)
| {{incode|abs(x)}}
| [https://en.wikipedia.org/wiki/Absolute_value Absolute value]
| [https://en.wikipedia.org/wiki/Absolute_value Absolute value]
| all
| all
|-
|-
| ceil(x)
| {{incode|ceil(x)}}
| [https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Ceiling function], smallest integer value greater than or equal to x
| [https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Ceiling function], smallest integer value greater than or equal to x
| all
| all
|-
|-
| floor(x)
| {{incode|floor(x)}}
| [https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Floor function], largest integer value less than or equal to x
| [https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Floor function], largest integer value less than or equal to x
| all
| all
|-
|-
| mod(x; y)
| {{incode|mod(x; y)}}
| [https://en.wikipedia.org/wiki/Remainder Remainder] after dividing ''x'' by ''y''
| [https://en.wikipedia.org/wiki/Remainder Remainder] after dividing ''x'' by ''y'', sign of result is that of the dividend.
| all, except y = 0
| all, except y = 0
|-
|-
| round(x)
| {{incode|round(x)}}
| [https://en.wikipedia.org/wiki/Rounding Rounding] to the nearest integer
| [https://en.wikipedia.org/wiki/Rounding Rounding] to the nearest integer
| all
| all
|-
|-
| trunc(x)
| {{incode|trunc(x)}}
| [https://en.wikipedia.org/wiki/Truncation Truncation] to the nearest integer in the direction of zero
| [https://en.wikipedia.org/wiki/Truncation Truncation] to the nearest integer in the direction of zero
| all
| all
|}
|}
{{Top}}
{{Top}}
<span id="Statistical_/_aggregate_functions"></span>
=== Funciones estadísticas/agregadas ===
=== Funciones estadísticas/agregadas ===


[https://en.wikipedia.org/wiki/Aggregate_function Aggregate functions] take one or more arguments.<br>
[https://en.wikipedia.org/wiki/Aggregate_function Aggregate functions] take one or more arguments.<br>


Individual arguments to aggregate functions may consist of ranges of cells. A range of cells is expressed as two cell references separated by a colon {{Incode|:}}, for example {{Incode|average(B1:B8)}} or {{Incode|sum(A1:A4; B1:B4)}}.
Individual arguments to aggregate functions may consist of ranges of cells. A range of cells is expressed as two cell references separated by a colon {{Incode|:}}, for example {{Incode|average(B1:B8)}} or {{Incode|sum(A1:A4; B1:B4)}}.
The cell references may also use cell aliases, for example {{Incode|average(StartTemp:EndTemp)}}.
The cell references may also use cell aliases, for example {{Incode|average(StartTemp:EndTemp)}}.


Las siguientes funciones agregadas son soportadas:
The following aggregate functions are supported:


{| class="wikitable"
{| class="wikitable"
!style="width: 20%;"|Function
!style="width: 20%;"|Function
!style="width: 55%;"|Description
!style="width: 55%;"|Description
!style="width: 25%;"|Value range
!style="width: 25%;"|Input range
|-
|-
| average(a; b; c; ...)
| {{incode|average(a; b; c; ...)}}
| [https://en.wikipedia.org/wiki/Arithmetic_mean Average] value of the arguments; same as sum(a; b; c; ...) / count(a; b; c; ...)
| [https://en.wikipedia.org/wiki/Arithmetic_mean Average] value of the arguments, same as sum(a; b; c; ...) / count(a; b; c; ...)
| all
| all
|-
|-
| count(a; b; c; ...)
| {{incode|count(a; b; c; ...)}}
| [https://en.wikipedia.org/wiki/Counting Count] of the arguments; typically used for cell ranges
| [https://en.wikipedia.org/wiki/Counting Count] of the arguments, typically used for cell ranges
| all
| all
|-
|-
| max(a; b; c; ...)
| {{incode|max(a; b; c; ...)}}
| [https://en.wikipedia.org/wiki/Maxima_and_minima Maximum] value of the arguments
| [https://en.wikipedia.org/wiki/Maxima_and_minima Maximum] value of the arguments
| all
| all
|-
|-
| min(a; b; c; ...)
| {{incode|min(a; b; c; ...)}}
| [https://en.wikipedia.org/wiki/Maxima_and_minima Minimum] value of the arguments
| [https://en.wikipedia.org/wiki/Maxima_and_minima Minimum] value of the arguments
| all
| all
|-
|-
| stddev(a; b; c; ...)
| {{incode|stddev(a; b; c; ...)}}
| [https://en.wikipedia.org/wiki/standard_deviation Standard deviation] of the values of the arguments
| [https://en.wikipedia.org/wiki/standard_deviation Standard deviation] of the values of the arguments
| all
| all
|-
|-
| sum(a; b; c; ...)
| {{incode|sum(a; b; c; ...)}}
| [https://en.wikipedia.org/wiki/Summation Sum] of the values of the arguments; typically used for cell ranges
| [https://en.wikipedia.org/wiki/Summation Sum] of the values of the arguments, typically used for cell ranges
| all
| all
|}
|}
{{Top}}
{{Top}}
<span id="String_manipulation"></span>
=== String manipulation ===
=== Manipulación de cadenas ===


<span id="String_identification"></span>
==== String identification ====
==== Identificación de cadena ====


Las cadenas se identifican en las expresiones rodeándolas con comillas angulares dobles de apertura/cierre (al igual que las etiquetas).
Strings are identified in expressions by surrounding them with opening/closing double chevrons (as are labels).


In following example, "TEXT" is recognized as a string : {{incode|<<TEXT>>}}
En el siguiente ejemplo, "TEXTO" se reconoce como una cadena: {{incode|<<TEXTO>>}}


<span id="String_concatenation"></span>
==== String concatenation ====
==== Concatenación de cadenas ====


Las cadenas se pueden concatenar usando el signo '+'.
Strings can be concatenated using the '+' sign.


Following example {{incode|<<MY>> + <<TEXT>>}} will be concatenated to "MYTEXT".
El siguiente ejemplo {{incode|<<MI>> + <<TEXTO>>}} se concatenará con "MITEXTO".


<span id="String_conversion"></span>
==== String conversion ====
==== Conversión de cadenas ====


Numerical values can be converted to strings with the {{incode|str}} function:
Los valores numéricos se pueden convertir en cadenas con la función {{incode|str}}:


{{incode|str(Box.Length.Value)}}
{{incode|str(Box.Length.Value)}}


<span id="String_formatting"></span>
==== String formatting ====
==== Formato de cadena ====


El formato de cadena se admite utilizando el estilo (antiguo) % de Python.
String formatting is supported using the (old) %-style Python way.


All %-specifiers as defined in [https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting Python documentation].
Todos los especificadores % tal como se definen en la [https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting documentación de Python].


As an example, supposing you have a default 10mm-side cube named 'Box' (default FreeCAD naming), the following expression {{incode|<<Cube length : %s>> % Box.Length}} will expand to "Cube length : 10.0 mm"
Como ejemplo, supongamos que tiene un cubo predeterminado de 10 mm de lado llamado 'Box' (nombramiento predeterminado de FreeCAD), la siguiente expresión {{incode|<<Longitud del cubo: %s>> % Box.Length}} se expandirá a "Longitud del cubo: 10.0 mm"


For more than one %-specifier use the following syntax: {{incode|<<Cube length is %s and width is %s>> % tuple(Box.Length; Box.Width)}}. Or use concatenation: {{incode|<<Cube length is %s>> % Box.Length + << and width is %s>> % Box.Width}}. Both will expand to "Cube length is 10.0 mm and width is 10.0 mm".
Para más de un especificador % utilice la siguiente sintaxis: {{incode|<<La longitud del cubo es %s y el ancho es %s>> % tuple(Box.Length; Box.Width)}}. O use concatenación: {{incode|<<La longitud del cubo es %s>> % Box.Length + << y el ancho es %s>> % Box.Width}}. Ambos se expandirán a "La longitud del cubo es de 10.0 mm y el ancho es de 10.0 mm".


A FreeCAD sample file using string formatting is available [https://forum.freecadweb.org/viewtopic.php?f=8&t=58657 in the forum]
Está disponible un archivo de muestra de FreeCAD que utiliza formato de cadena [https://forum.freecadweb.org/viewtopic.php?f=8&t=58657 en el foro]
{{Top}}
{{Top}}
<span id="Object_creation_functions"></span>
=== Create function ===
=== Funciones de creación de objetos ===


Los siguientes objetos se pueden crear en expresiones utilizando las siguientes funciones:
The following objects may be created in expressions via the {{incode|create}} function:
* Vector
* Matrix
* Rotation
* Placement


{| class="wikitable"
The {{incode|create}} function passes subsequent arguments to the underlying Python constructor when creating the object.
! Type
! Function
! Description
|-
| {{incode|Tuple}}
| {{incode|tuple(a; b; ...)}}
| Example: {{incode|tuple(2; 1; 2)}}
|-
| {{incode|List}}
| {{incode|list(a; b; ...)}}
| Example: {{incode|list(2; 1; 2)}}
|-
| rowspan="2" | [[Vector API|{{incode|Vector}}]]
| {{incode|vector(x; y; z)}}
| rowspan="2" | Create a vector using three unit-less or {{incode|Length}} unit values.
Example: {{incode|vector(2; 1; 3)}}
|-
| {{incode|create(<<vector>>; x; y; z)}}
|-
| rowspan="2" | [[Matrix API|{{incode|Matrix}}]]
|
matrix(
a<sub>11</sub>; a<sub>12</sub>; a<sub>13</sub>; a<sub>14</sub>;
a<sub>21</sub>; a<sub>22</sub>; a<sub>23</sub>; a<sub>24</sub>;
a<sub>31</sub>; a<sub>32</sub>; a<sub>33</sub>; a<sub>34</sub>;
a<sub>41</sub>; a<sub>42</sub>; a<sub>43</sub>; a<sub>44</sub>
)
| rowspan="2" | Create a 4x4 matrix in [https://en.wikipedia.org/wiki/Row-_and_column-major_order row-major order]:
<math>
\begin{bmatrix}
a_{11} & a_{12} & a_{13} & a_{14} \\
a_{21} & a_{22} & a_{23} & a_{24} \\
a_{31} & a_{32} & a_{33} & a_{34} \\
a_{41} & a_{42} & a_{43} & a_{44} \\
\end{bmatrix}
</math>


Se puede proporcionar un mínimo de 1 argumento, como {{incode|matrix(1)}}, que crea una matriz de identidad.
Various mathematical operations such as multiplication, addition, and subtraction are supported via standard mathematical operators (e.g. {{incode|*}}, {{incode|+}}, {{incode|-}}).


Example: {{incode|matrix(1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16)}}
==== Vector ====
|-
| {{incode|create(<<matrix>>; a<sub>11</sub>; a<sub>12</sub>; ...; a<sub>44</sub>)}}
|-
| rowspan="4" | {{incode|Rotation}}
| {{incode|rotation(axis; angle)}}
| rowspan="4" | Create a {{incode|Rotation}} by specifying its {{incode|axis}} ({{incode|Vector}}) and {{incode|angle}} ({{incode|Angle}} unit or unit-less), or three Euler angles {{incode|α}}, {{incode|β}}, {{incode|γ}}.
Examples:
* {{incode|rotation(vector(0; 1; 0); 45)}}
* {{incode|create(<<rotation>>; 30; 30; 30)}}
|-
| {{incode|rotation(α; β; γ)}}
|-
| {{incode|create(<<rotation>>; axis; angle)}}
|-
| {{incode|create(<<rotation>>; α; β; γ)}}
|-
| rowspan="5" | [[Placement_API|{{incode|Placement}}]]
| {{incode|placement(base; rotation)}}
| rowspan="5" | Create a {{incode|Placement}} with various parameters, including:
* {{incode|base}}: base location ({{incode|Vector}})
* {{incode|center}}: center location ({{incode|Vector}})
* {{incode|rotation}}: {{incode|Rotation}}
* {{incode|axis}}: Rotation axis ({{incode|Vector}})
* {{incode|angle}}: Rotation angle (unit-less or {{incode|Angle}} unit value)
* {{incode|matrix}}: {{incode|Matrix}}


Examples:
When {{incode|create}} is passed {{incode|<<vector>>}} as the 1st argument, the next 3 arguments are the X, Y, and Z coordinates for the {{incode|Vector}} respectively.
* {{incode|placement(vector(2; 1; 3); rotation(vector(0; 0; 1); 45))}}

* {{incode|create(<<placement>>; create(<<vector>>; 2; 1; 2); create(<<rotation>>; create(<<vector>>; 0; 1; 0); 45))}}
Example:
|-
| {{incode|placement(base; rotation; center)}}
|-
| {{incode|placement(base; axis; angle)}}
|-
| {{incode|placement(matrix)}}
|-
| {{incode|create(<<placement>>; ...)}}
|}
{{Top}}
<span id="Vector_functions"></span>
=== Funciones vectoriales ===


<div class="mw-translate-fuzzy">
{{incode|create(<<vector>>; 2; 1; 2)}}
Funciones: {{Version|0.22}}.

</div>
==== Matrix ====

When {{incode|create}} is passed {{incode|<<matrix>>}} as the 1st argument, the next 16 arguments are the elements for the {{incode|Matrix}} in [https://en.wikipedia.org/wiki/Row-_and_column-major_order row-major order].

Example:

{{incode|create(<<matrix>>; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16)}}

==== Rotation ====

When {{incode|create}} is passed {{incode|<<rotation>>}} as the 1st argument, there are two ways to create a {{incode|Rotation}}:

1. Specify an axis vector and a rotation angle.

Example:

{{incode|create(<<rotation>>; create(<<vector>>; 0; 1; 0); 45)}}

2. Specify 3 rotations about the X, Y, and Z axes as Euler angles.

Example:

{{incode|create(<<rotation>>; 30; 30; 30)}}

==== Placement ====

When {{incode|create}} is passed {{incode|<<placement>>}} as the 1st argument, there are five ways to create a {{incode|Placement}}.

These possible combinations are documented in the below table and are based on the [[Placement_API|Placement API]] page.


{| class="wikitable"
{| class="wikitable"
! Function / Operator
!style="width: 33%;"|Number of arguments
!style="width: 66%;"|Description
! Description
|-
|-
| {{incode|v1 + v2}}
| 2
| Add two vectors.
| {{incode|create(<<placement>>; Placement)}}
|-
|-
| {{incode|v1 - v2}}
| 2
| Subtract two vectors.
| {{incode|create(<<placement>>; Matrix)}}
|-
|-
| {{incode|v * s}}
| 3
| Uniformly scale a vector by {{incode|s}}.
| {{incode|create(<<placement>>; Base; Rotation)}}
|-
|-
| {{incode|vangle(v1; v2)}}
| 4
| Angle between two vectors in degrees.
| {{incode|create(<<placement>>; Base; Rotation; Center)}}
|-
|-
| {{incode|vcross(v1; v2)}}
| 4
| Cross product of two vectors <math>v_1 \times v_2</math>.
| {{incode|create(<<placement>>; Base; Axis; Angle)}}
|-
| {{incode|v1 * v2}}
| rowspan="2" | Dot product of two vectors <math>v_1 \cdot v_2</math>.
|-
| {{incode|vdot(v1; v2)}}
|-
| {{incode|vlinedist(v1; v2; v3)}}
| Distance between vector {{incode|v1}} and a line through {{incode|v2}} in direction {{incode|v3}}.
|-
| {{incode|vlinesegdist(v1; v2; v3)}}
| Distance between vector {{incode|v1}} and the closest point on a line segment from {{incode|v2}} to {{incode|v3}}.
|-
| {{incode|vlineproj(v1; v2; v3)}}
| Project vector {{incode|v1}} on a line through {{incode|v2}} in direction {{incode|v3}}.
|-
| {{incode|vnormalize(v)}}
| Normalize a vector to a unit vector.
|-
| {{incode|vplanedist(v1)}}
| Distance between vector {{incode|v1}} and a plane defined by a point {{incode|v2}} and a normal {{incode|v3}}.
|-
| {{incode|vplaneproj(v1)}}
| Project vector {{incode|v1}} on a plane defined by a point {{incode|v2}} and a normal {{incode|v3}}.
|-
| {{incode|vscale(v; sx; sy; sz)}}
| rowspan="4" | Non-uniformly scale a vector by {{incode|sx}} in the X direction, {{incode|sy}} in the Y direction, and {{incode|sz}} in the Z direction.
|-
| {{incode|vscalex(v; sx)}}
|-
| {{incode|vscaley(v; sy)}}
|-
| {{incode|vscalez(v; sz)}}
|}
|}

The following example shows the syntax for creating a {{incode|Placement}} from a {{incode|Base}} (vector) and a {{incode|Rotation}}:

{{incode|create(<<placement>>; create(<<vector>>; 2; 1; 2); create(<<rotation>>; create(<<vector>>; 0; 1; 0); 45))}}

For readability, you can define vectors and rotations in separate cells, and then reference the cells in your expression.
{{Top}}
{{Top}}
<span id="Matrix_functions"></span>
=== Matrix functions ===
=== Funciones matriciales ===


{{incode|Rotation}} and {{incode|Placement}} can each be represented by a {{incode|Matrix}}. The following functions all take in a {{incode|Matrix}}, {{incode|Rotation}}, or {{incode|Placement}} as their first parameter denoted in the table below by {{incode|m}}. The type of the returned object is the same as the object supplied in the first argument except when using {{incode|mtranslate}} on a {{incode|Rotation}}, in which case a {{incode|Placement}} will be returned.
==== mscale ====


{| class="wikitable"
Scale a {{incode|Matrix}} with a given {{incode|Vector}}.
! Function

! Description
{{incode|mscale(Matrix; Vector)}}
|-

{{incode|mscale(Matrix; x; y; z)}}
| {{incode|minvert(m)}}
| Calculate the [https://en.wikipedia.org/wiki/Invertible_matrix Inverse matrix].

|-
==== minvert ====
| {{incode|mrotate(m; rotation)}}

| rowspan="3" | [https://en.wikipedia.org/wiki/Transformation_matrix#Rotation_2 Rotate] by either:
Invert the given {{incode|Matrix}}, {{incode|Rotation}}, or {{incode|Placement}}.
* a {{incode|Rotation}}

* an axis ({{incode|Vector}}) and an angle ({{incode|Angle}} unit or unit-less)
{{incode|minvert(Matrix)}}
* three Euler angles {{incode|α}}, {{incode|β}}, {{incode|γ}}

|-
{{incode|minvert(Rotation)}}
| {{incode|mrotate(m; axis; angle)}}

|-
{{incode|minvert(Placement)}}
| {{incode|mrotate(m; α; β; γ)}}
{{Top}}
|-
=== Tuple & list ===
| {{incode|mrotatex(m; angle)}}

| [https://en.wikipedia.org/wiki/Transformation_matrix#Rotation_2 Rotate] around the X axis.
You can create Python {{incode|tuple}} or {{incode|list}} objects via their respective functions.
|-

{{incode|tuple(2; 1; 2)}}
| {{incode|mrotatey(m; angle)}}
| [https://en.wikipedia.org/wiki/Transformation_matrix#Rotation_2 Rotate] around the Y axis.

|-
{{incode|list(2; 1; 2)}}
| {{incode|mrotatez(m; angle)}}
| [https://en.wikipedia.org/wiki/Transformation_matrix#Rotation_2 Rotate] around the Z axis.
|-
| {{incode|mtranslate(m; vector)}}
| rowspan="2" | [https://en.wikipedia.org/wiki/Translation_(geometry)#Matrix_representation Translate] by a {{incode|vector}} ({{incode|Vector}}) or X, Y, Z values. If a {{incode|Rotation}} is translated, the returned object is a {{incode|Placement}}.
|-
| {{incode|mtranslate(m; x; y; z)}}
|-
| {{incode|mscale(m; vector)}}
| rowspan="2" | [https://en.wikipedia.org/wiki/Scaling_(geometry)#Matrix_representation Scale] by a {{incode|vector}} ({{incode|Vector}}) or X, Y, Z values.
|-
| {{incode|mscale(m; x; y; z)}}
|}
{{Top}}
{{Top}}
<span id="Conditional_expressions"></span>
== Expresiones condicionales ==
== Expresiones condicionales ==


Conditional expressions are of the form {{incode|condition ? resultTrue : resultFalse}}. The condition is defined as an expression that evaluates to either {{incode|0}} (false) or non-zero (true). Note that enclosing the conditional expression in parentheses is currently considered an error.
Conditional expressions are of the form {{incode|condition ? resultTrue : resultFalse}}. The condition is defined as an expression that evaluates to either {{incode|0}} (false) or non-zero (true).


The following [https://en.wikipedia.org/wiki/Relational_operator#Standard_relational_operators relational operators] are defined:
The following [https://en.wikipedia.org/wiki/Relational_operator#Standard_relational_operators relational operators] are defined:
Line 401: Line 504:
|}
|}
{{Top}}
{{Top}}
<span id="Units"></span>
== Unidades ==
== Unidades ==


Units can be used directly in expressions. The parser connects them to the previous value. So {{incode|2mm}} or {{incode|2 mm}} is valid while {{incode|mm}} is invalid because there is no preceding value.
Las unidades se pueden utilizar directamente en expresiones. El analizador los conecta con el valor anterior. Entonces {{incode|2mm}} o {{incode|2 mm}} es válido mientras que {{incode|mm}} no es válido porque no hay un valor anterior.


All values must have a unit. Therefore you must in general use a unit for values in spreadsheets.<br/>
All values must have a unit. Therefore you must in general use a unit for values in spreadsheets.<br/>
In some cases it works even without a unit, for example if you have e.g. in spreadsheet cell B1 just the number {{incode|1.5}} and refer to it for a pad height. This only works because the pad height predefines the unit {{incode|mm}} that is used if no unit is given. It will nevertheless fail if you use for the pad height e.g. {{incode|Sketch1.Constraints.Width - Spreadsheet.B1}} because {{incode|Sketch1.Constraints.Width}} has a unit and {{incode|Spreadsheet.B1}} has not.
In some cases it works even without a unit, for example if you have e.g. in spreadsheet cell B1 just the number {{incode|1.5}} and refer to it for a pad height. This only works because the pad height predefines the unit {{incode|mm}} that is used if no unit is given. It will nevertheless fail if you use for the pad height e.g. {{incode|Sketch1.Constraints.Width - Spreadsheet.B1}} because {{incode|Sketch1.Constraints.Width}} has a unit and {{incode|Spreadsheet.B1}} has not.


Units with exponents can directly be entered. So e.g. {{incode|mm^3}} will be recognized as mm³ and {{incode|m^3}} will be recognized as m³.
Se pueden ingresar directamente unidades con exponentes. Entonces, por ejemplo, {{incode|mm^3}} se reconocerá como mm³ y {{incode|m^3}} se reconocerá como m³.


If you have a variable whose name is that of a unit you must put the variable between {{incode|<< >>}} to prevent it from being recognized as a unit. For example if you have the dimension {{incode|Sketch.Constraints.A}} it would be recognized as the unit ampere. Therefore you must write it in the expression as {{incode|Sketch.Constraints.<<A>>}}.
Si tienes una variable cuyo nombre es el de una unidad debes poner la variable entre {{incode|<< >>}} para evitar que sea reconocida como una unidad. Por ejemplo, si tiene la dimensión {{incode|Sketch.Constraints.A}}, se reconocerá como la unidad amperio. Por lo tanto debes escribirlo en la expresión como {{incode|Sketch.Constraints.<<A>>}}.


El analizador de expresiones reconoce las siguientes unidades:
The following units are recognized by the expression parser:


<span id="Amount_of_substance"></span>
=== Amount of substance ===
=== Cantidad de sustancia ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
!style="width: 66%;"|Description
|-
| mmol
| Milli[https://en.wikipedia.org/wiki/Mole_(unit) mole]
|-
|-
| mol
| mol
Line 424: Line 532:
|}
|}


=== Angle ===
<span id="Angle"></span>
=== Ángulo ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
Line 455: Line 564:
|}
|}


=== Current ===
<span id="Current"></span>
=== Corriente ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
Line 474: Line 584:
|}
|}


<span id="Electric_capacitance"></span>
=== Energy/work ===
=== Capacitancia electrica ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
!style="width: 66%;"|Description
|-
| pF
| Pico[https://en.wikipedia.org/wiki/Farad farad]
|-
| nF
| Nano[https://en.wikipedia.org/wiki/Farad farad]
|-
| uF
| Micro[https://en.wikipedia.org/wiki/Farad farad]; alternative to the unit µF
|-
| µF
| Micro[https://en.wikipedia.org/wiki/Farad farad]; alternative to the unit uF
|-
| mF
| Milli[https://en.wikipedia.org/wiki/Farad farad]
|-
| F
| [https://en.wikipedia.org/wiki/Farad Farad]; 1 F = 1 s^4·A^2/m^2/kg
|}

<span id="Electric_charge"></span>
=== Carga eléctrica ===

{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
|-
| C
| [https://en.wikipedia.org/wiki/Coulomb Coulomb]; 1 C = 1 A*s
|}

<span id="Electric_conductivity"></span>
=== Conductividad eléctrica ===

{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
|-
| uS
| Micro[https://en.wikipedia.org/wiki/Siemens_(unit) siemens]; alternative to the unit µS
|-
| µS
| Micro[https://en.wikipedia.org/wiki/Siemens_(unit) siemens]; alternative to the unit uS
|-
| mS
| Milli[https://en.wikipedia.org/wiki/Siemens_(unit) siemens]
|-
| S
| [https://en.wikipedia.org/wiki/Siemens_(unit) Siemens]; 1 S = 1 s^3·A^2/kg/m^2
|-
| kS
| Kilo[https://en.wikipedia.org/wiki/Siemens_(unit) Siemens]
|-
| MS
| Mega[https://en.wikipedia.org/wiki/Siemens_(unit) Siemens]
|}

<span id="Electric_inductance"></span>
=== Inductancia eléctrica ===

{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
|-
| nH
| Nano[https://en.wikipedia.org/wiki/Henry_(unit) henry]
|-
| uH
| Micro[https://en.wikipedia.org/wiki/Henry_(unit) henry]; alternative to the unit µH
|-
| µH
| Micro[https://en.wikipedia.org/wiki/Henry_(unit) henry]; alternative to the unit uH
|-
| mH
| Milli[https://en.wikipedia.org/wiki/Henry_(unit) henry]
|-
| H
| [https://en.wikipedia.org/wiki/Henry_(unit) Henry]; 1 H = 1 kg·m^2/s^2/A^2
|}

<span id="Electric_potential"></span>
=== Potencial eléctrico ===

{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
|-
| mV
| Milli[https://en.wikipedia.org/wiki/Volt volt]
|-
| V
| [https://en.wikipedia.org/wiki/Volt Volt]
|-
| kV
| Kilo[https://en.wikipedia.org/wiki/Volt volt]
|}

<span id="Electric_resistance"></span>
=== Resistencia electrica ===

{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
|-
| Ohm
| [https://en.wikipedia.org/wiki/Ohm Ohm]; 1 Ohm = 1 kg·m^2/s^3/A^2
|-
| kOhm
| Kilo[https://en.wikipedia.org/wiki/Ohm ohm]
|-
| MOhm
| Mega[https://en.wikipedia.org/wiki/Ohm ohm]
|}

<span id="Energy/work"></span>
=== Energía/trabajo ===

{| class="wikitable float-right mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
|-
| mJ
| Milli[https://en.wikipedia.org/wiki/Joule joule]
|-
|-
| J
| J
| [https://en.wikipedia.org/wiki/Joule Joule]
| [https://en.wikipedia.org/wiki/Joule Joule]
|-
| kJ
| Kilo[https://en.wikipedia.org/wiki/Joule joule]
|-
| eV
| [https://en.wikipedia.org/wiki/Electronvolt Electronvolt]; 1 eV = 1.602176634e-19 J
|-
| keV
| Kilo[https://en.wikipedia.org/wiki/Electronvolt electronvolt]
|-
| MeV
| Mega[https://en.wikipedia.org/wiki/Electronvolt electronvolt]
|-
| kWh
| [https://en.wikipedia.org/wiki/Kilowatt_hour Kilowatt hour]; 1 kWh = 3.6e6 J
|-
|-
| Ws
| Ws
Line 491: Line 740:
| CV
| CV
| [https://en.wikipedia.org/wiki/Joule Coulomb-volt]; alternative to the unit Joule
| [https://en.wikipedia.org/wiki/Joule Coulomb-volt]; alternative to the unit Joule
|-
| cal
| [https://en.wikipedia.org/wiki/Calorie Calorie]; 1 cal = 4.184 J
|-
| kcal
| Kilo[https://en.wikipedia.org/wiki/Calorie calorie]
|}
|}


=== Force ===
<span id="Force"></span>
=== Fuerza ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
Line 515: Line 771:
|}
|}


=== Length ===
<span id="Length"></span>
=== Longitud ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
Line 570: Line 827:
|}
|}


<span id="Luminous_intensity"></span>
=== Luminous intensity ===
=== Intensidad luminosa ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
Line 580: Line 838:
|}
|}


<span id="Magnetic_flux"></span>
=== Mass ===
=== Flujo magnético ===

{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
|-
| Wb
| [https://en.wikipedia.org/wiki/Weber_(unit) Weber]; 1 Wb = 1 kg*m^2/s^2/A
|}

<span id="Magnetic_flux_density"></span>
=== Densidad de flujo magnético ===

{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
|-
| G
| [https://en.wikipedia.org/wiki/Gauss_(unit) Gauss]; 1 G = 1 e-4 T
|-
| T
| [https://en.wikipedia.org/wiki/Tesla_(unit) Tesla]; 1 T = 1 kg/s^2/A
|}

<span id="Mass"></span>
=== Masa ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
Line 620: Line 904:
|}
|}


=== Power ===
<span id="Power"></span>
=== Potencia ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
Line 629: Line 914:
| [https://en.wikipedia.org/wiki/Watt Watt]
| [https://en.wikipedia.org/wiki/Watt Watt]
|-
|-
| VA
| kW
| [https://en.wikipedia.org/wiki/Volt-ampere Volt-ampere]
| Kilo[https://en.wikipedia.org/wiki/Watt watt]
|}
|}


=== Pressure ===
<span id="Pressure"></span>
=== Presión ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
Line 670: Line 956:
|}
|}


=== Temperature ===
<span id="Temperature"></span>
=== Temperatura ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
Line 689: Line 976:
|}
|}


<span id="Time"></span>
=== Time ===
=== Tiempo ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
Line 703: Line 991:
| h
| h
| [https://en.wikipedia.org/wiki/Hour Hour]
| [https://en.wikipedia.org/wiki/Hour Hour]
|-
| Hz (1/s)
| [https://en.wikipedia.org/wiki/Hertz Hertz]
|-
| kHz
| Kilo[https://en.wikipedia.org/wiki/Hertz hertz],
|-
| MHz
| Mega[https://en.wikipedia.org/wiki/Hertz hertz]
|-
| GHz
| Giga[https://en.wikipedia.org/wiki/Hertz hertz]
|-
| THz
| Tera[https://en.wikipedia.org/wiki/Hertz hertz]
|}
|}


=== Volume ===
<span id="Volume"></span>
=== Volumen ===


{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
!style="width: 66%;"|Description
|-
| ml
| Milli[https://en.wikipedia.org/wiki/Litre liter]
|-
|-
| l
| l
| [https://en.wikipedia.org/wiki/Litre Liter]
| [https://en.wikipedia.org/wiki/Litre Liter]
|-
| cft
| Cubic[https://en.wikipedia.org/wiki/Foot_(unit) foot]
|}

<span id="Special_imperial_units"></span>
=== Unidades imperiales especiales ===

{| class="wikitable mw-collapsible mw-collapsed"
!style="width: 33%;"|Unit
!style="width: 66%;"|Description
|-
| mph
| [https://en.wikipedia.org/wiki/Miles_per_hour Miles per hour]
|-
| sqft
| [https://en.wikipedia.org/wiki/Square_foot Square foot]
|}
|}


<span id="Unsupported_units"></span>
=== Unsupported units ===
=== Unidades no compatibles ===


The following commonly used units are not yet supported, for some an alternative is provided:
The following commonly used units are not yet supported, for some an alternative is provided:
Line 757: Line 1,082:
|}
|}
{{Top}}
{{Top}}
<span id="Invalid_characters_and_names"></span>
==Caracteres y nombres no válidos==
==Caracteres y nombres no válidos==


Line 763: Line 1,089:
In cases where you cannot use a label, such as the name of a sketch's constraints, you must be aware what characters are not allowed.
In cases where you cannot use a label, such as the name of a sketch's constraints, you must be aware what characters are not allowed.


<span id="Labels"></span>
===Etiquetas===
===Etiquetas===


Line 776: Line 1,103:
For example, the label {{incode|Sketch\002}} must be referenced as {{incode|<<Sketch\\002>>}}.
For example, the label {{incode|Sketch\002}} must be referenced as {{incode|<<Sketch\\002>>}}.


<span id="Names"></span>
===Nombres===
===Nombres===


Line 784: Line 1,112:
!style="width: 66%;"|Description
!style="width: 66%;"|Description
|-
|-
| '''+''', '''-''', '''*''', '''/''', '''^''', '''_''', '''<''', '''>''', '''(''', ''')''', '''{''', '''}''', '''[''', ''']''', '''.''', ''',''', '''='''
| '''+''', '''-''', '''*''', '''/''', '''^''', '''_''', '''<''', '''>''', '''(''', ''')''', '''{''', '''}''', '''[''', ''']''', '''.''', ''',''', '''='''
| Characters that are math operators or part of mathematical constructs
| Characters that are math operators or part of mathematical constructs
|-
|-
Line 811: Line 1,139:
See [[Spreadsheet_SetAlias#Usage|Spreadsheet SetAlias]].
See [[Spreadsheet_SetAlias#Usage|Spreadsheet SetAlias]].
{{Top}}
{{Top}}
<span id="Reference_to_CAD_data"></span>
== Referencia a los datos CAD ==
== Referencia a los datos CAD ==


It is possible to use data from the model itself in an expression. To reference a property use{{incode|object.property}}. If the property is a compound of fields, the individual fields can be accessed as {{incode|object.property.field}}.
It is possible to use data from the model itself in an expression. To reference a property use {{incode|object_name.property}} or {{incode|<<object_label>>.property}}, labels must be enclosed in {{incode|<<}} and {{incode|>>}}. If you want to use labels they must be unique.


All next examples reference the object by its name, but in all cases the object label can also be used.
The following table shows some examples:

If the property is a compound of fields, the individual fields can be accessed as {{incode|object_name.property.field}}.

Para referenciar una lista de objetos use {{incode|object_label.list[list_index]}}. Si quiere por ejemplo referenciar una restricción de un croquis use {{incode|Sketch.Constraints[16]}}. Si está en el mismo croquis puede omitir su nombre y solo usar {{incode|Constraints[16]}}.Note que el índice inicia en 0, por lo que la restricción 17 tiene que ser referenciada como {{incode|Constraints[16]}}

To reference the object itself use the {{incode|_self}} pseudo property: {{incode|object_name._self}}.

The following table shows some more examples:
{| class="wikitable"
{| class="wikitable"
!CAD data
!CAD data
Line 821: Line 1,158:
!Result
!Result
|-
|-
|Parametric Length of a Part-Workbench Cube
|Length of a [[Part_Box|Part Box]]
|{{incode|Cube.Length}}
|{{incode|Box.Length}}
|Length with units mm
|Length with units (mm)
|-
|-
|Volume of the Cube
|Volume of the Box
|{{incode|Cube.Shape.Volume}}
|{{incode|Box.Shape.Volume}}
|Volume in mm&sup3; without units
|Volume in mm&sup3; without units
|-
|-
|Type of the Cube-shape
|Shape type of the Box
|{{incode|Cube.Shape.ShapeType}}
|{{incode|Box.Shape.ShapeType}}
|String: Solid
|String: Solid
|-
|-
|Label of the Cube
|Label of the Box
|{{incode|Cube.Label}}
|{{incode|Box.Label}}
|String: Label
|String: Label
|-
|-
|X-coordinate of center of mass of the Cube
|X-coordinate of center of mass of the Box
|{{incode|Cube.Shape.CenterOfMass.x}}
|{{incode|Box.Shape.CenterOfMass.x}}
|X-coordinate in mm without units
|X-coordinate in mm without units
|-
|-
|X-coordinate of the Box placement
|Full Cube object
|{{incode|Cube._self}}
|{{incode|Box.Placement.Base.x}}
|X-coordinate with units (mm)
|-
|X-component of the rotation axis of the Box placement
|{{incode|Box.Placement.Rotation.Axis.x}}
|X-component of the unit vector in mm without units
|-
|Rotation angle of the Box placement
|{{incode|Box.Placement.Rotation.Angle}}
|Rotation angle with units (deg)
|-
|Full Box object
|{{incode|Box._self}}
|Object of type <Part::PartFeature>
|Object of type <Part::PartFeature>
|-
|-
Line 861: Line 1,210:
|Value of the {{PropertyData|Length}} property in e.g a Pad object, if the expression is used in e.g {{PropertyData|Length2}} in the same object.
|Value of the {{PropertyData|Length}} property in e.g a Pad object, if the expression is used in e.g {{PropertyData|Length2}} in the same object.
|}
|}

=== Cyclic dependencies ===

FreeCAD checks dependencies based on the relationship between document objects, not properties. This means that you cannot provide data to an object and query that same object for results. For example, even though there are no cyclic dependencies when the properties themselves are considered, you may not have an object which gets its dimensions from a spreadsheet and then display the volume of that object in the same spreadsheet. You have to use two spreadsheets, one to drive your model and the other for reporting.

As a workaround it is possible to display a cell range from the second spreadsheet in the first (or vice versa) by creating a [[Spreadsheet_Workbench#Cell_binding|cell binding]] with the {{MenuCommand|Hide dependency of binding}} option.

Another way to workaround cyclic dependencies is to hide the reference by using the {{incode|href}} or {{incode|hiddenref}} function for individual expressions, for example: {{incode|href(Box.Length)}}.

Please note that both mentioned workarounds should be used with caution, and that they do not work if the properties that are reported depend on dimensions that are driven from the same spreadsheet.
{{Top}}
{{Top}}
<span id="Document-wide_global_variables"></span>
== Variables globales de todo el documento ==
== Variables globales de todo el documento ==


There is no concept of global variables in FreeCAD at the moment. Instead, arbitrary variables can be defined as cells in a spreadsheet using the [[Spreadsheet Workbench|Spreadsheet workbench]], and then be given a name using the alias property for the cell (right-click on cell). Then they can be accessed from any expression just as any other object property.
There is no concept of global variables in FreeCAD at the moment. Instead, arbitrary variables can be defined as cells in a spreadsheet using the [[Spreadsheet Workbench|Spreadsheet workbench]], and then be given a name using the alias property for the cell (right-click on cell). Then they can be accessed from any expression just as any other object property.
{{Top}}
{{Top}}
<span id="Cross-document_linking"></span>
== Enlace entre documentos ==
== Enlace entre documentos ==


It is possible (with limitations) to define a Property of an object in your current document (".FCstd" file) by using an Expression to reference a Property of an object contained in a different document (".FCstd" file). For example, a cell in a spreadsheet or the {{PropertyData|Length}} of a Part Cube, etc. in one document can be defined by an Expression that references the X Placement value or another Property of an object contained in a different document.
It is possible (with limitations) to define a Property of an object in your current document (".FCstd" file) by using an Expression to reference a Property of an object contained in a different document (".FCstd" file). For example, a cell in a spreadsheet or the {{PropertyData|Length}} of a Part Cube, etc. in one document can be defined by an Expression that references the X Placement value or another Property of an object contained in a different document.


A document's name is used to reference it from other documents. When saving a document the first time, you choose a file name; this is usually different from the initial default "Unnamed1" (or its translated equivalent). To prevent links being lost when the master document is renamed upon saving, it is recommended that you first create the master document, create a spreadsheet inside it, and save it. Subsequently, you can still make changes to the file and its spreadsheet but you should not rename it.
A document's name is used to reference it from other documents. When saving a document the first time, you choose a file name; this is usually different from the initial default "Unnamed1" (or its translated equivalent). To prevent links being lost when the master document is renamed upon saving, it is recommended that you first create the master document, create a spreadsheet inside it, and save it. Subsequently, you can still make changes to the file and its spreadsheet but you should not rename it.


Once the master document with the spreadsheet is created and saved (named), it is safe to create dependent documents. For example, assuming you name the master document {{incode|master}}, the spreadsheet {{incode|modelConstants}}, and give a cell an alias-name {{incode|Length}}, you can then access the value as:
Once the master document with the spreadsheet is created and saved (named), it is safe to create dependent documents. For example, assuming you name the master document {{incode|master}}, the spreadsheet {{incode|modelConstants}}, and give a cell an alias-name {{incode|Length}}, you can then access the value as:
Line 876: Line 1,237:
{{incode|master#modelConstants.Length}}
{{incode|master#modelConstants.Length}}


'''Note:''' that the master document must be loaded for the values in the master to be available to the dependent document.
Note that the master document must be loaded for the values in the master to be available to the dependent document.

Unfortunately, the integrated checker sometimes claims that a valid name doesn't exist. Continue typing anyway. When you have completed the full reference, the {{Button|OK}} button will become active.


Of course, it's up to you to load the corresponding documents later when you want to change anything.
Of course, it's up to you to load the corresponding documents later when you want to change anything.
{{Top}}
{{Top}}
<span id="Known_issues_/_remaining_tasks"></span>
== Problemas conocidos / tareas pendientes ==
== Problemas conocidos / tareas pendientes ==


* The dependency graph is based on the relationship between document objects, not properties. This means that you cannot provide data to an object and query that same object for results. For example, even though there are no cyclic dependencies when the properties themselves are considered, you may not have an object which gets its dimensions from a spreadsheet and then display the volume of that object in the same spreadsheet. As a work-around use multiple spreadsheets, one to drive your model and the other for reporting.
* The expression parser does not handle parentheses well, and is unable to properly parse some expressions. For example: {{incode|<nowiki>=</nowiki> (A1 > A2) ? 1 : 0}} results in an error, while {{incode|<nowiki>=</nowiki> A1 > A2 ? 1 : 0}} is accepted. The expression {{incode|<nowiki>=</nowiki> 5 + ((A1>A2) ? 1 : 0)}} cannot be entered in any form.
* As stated above, unfortunately, the integrated checker sometimes claims that a valid name doesn't exist. Continue typing anyway. When you have completed the full reference, the {{Button|OK}} button will become active.
* FreeCAD does not yet have a built-in expression manager where all expressions in a document are listed, and can be created, deleted, queried, etc. But an addon is available: [https://github.com/gbroques/fcxref fcxref expression manager].
* FreeCAD does not yet have a built-in expression manager where all expressions in a document are listed, and can be created, deleted, queried, etc. But an addon is available: [https://github.com/gbroques/fcxref fcxref expression manager].
* Open bugs/tickets for Expressions can be found in the [https://freecadweb.org/tracker/set_project.php?project_id=4;20 FreeCAD Bugtracker Expressions category]
* Open bugs/tickets for Expressions can be found on [https://github.com/FreeCAD/FreeCAD/issues?q=is%3Aissue+is%3Aopen+label%3AExpressions GitHub].
{{Top}}
{{Top}}



Latest revision as of 10:03, 21 April 2024

Resumen

Es posible definir propiedades utilizando expresiones matemáticas. En la interfaz gráfica de usuario, los cuadros de giro o campos de entrada que están vinculados a las propiedades contienen un icono azul . Haciendo clic en el icono o escribiendo el signo igual = aparece el editor de expresiones para esa propiedad en particular.

Es una expresión matemática que usa la notación de los operadores, funciones y constantes predefinidas matemáticas estándar como se describe a continuación. Además, la expresión puede hacer referencia a otras propiedades de objetos, y también utilizar condicionales. Los números en una expresión pueden tener una unidad opcional adjunta.

Los números pueden usar ya sea una coma , o un punto decimal . para separar los dígitos enteros de los decimales. Cuando se usa el marcador decimal, debe ser seguido por al menos un dígito. Por lo tanto, las expresiones 1.+2. y 1,+2, son inválidas, pero 1.0+2.0 y 1,0+2,0 son válidas.

Los operadores y las funciones son conscientes de la unidad y requieren combinaciones válidas de unidades, si se suministran. Por ejemplo, 2mm+4mm es una expresión válida, mientras que 2mm+4 no lo es. Esto también se aplica a las referencias a propiedades de objetos que tienen unidades, como las propiedades de longitud. Por lo tanto, Pad001.Length + 1 es inválido ya que agrega un número puro a una propiedad con unidades de longitud, se requiere Pad001.Length + 1mm.

Algunos errores relacionados con las unidades pueden parecer poco intuitivos, ya que las expresiones se rechazan o producen resultados que no coinciden con las unidades de la propiedad que se establece. Aquí hay unos ejemplos:

1/2mm no se interpreta como medio milímetro sino como 1/(2mm), lo que da como resultado: 0.5 mm^-1.

sqrt(2)mm no es válido porque la llamada a la función no es un número. Esto debe ingresarse como sqrt(2) * 1mm.

Argumentos de la función

Múltiples argumentos a una función pueden estar separados por un punto y coma ; o una coma seguida por un espacio , . En el último caso, la coma se convierte a un punto y coma después de la entrada. Cuando se usa un punto y coma, no es necesario un espacio final.

Los argumentos pueden incluir referencias a las celdas en una hoja de cálculo. Una referencia de celda consiste en la letra mayúscula de fila de la celda seguida de su número de columna, por ejemplo A1. También se puede hacer referencia a una celda utilizando el alias de la celda, por ejemplo, Spreadsheet.MyPartWidth.

Referencia de objetos

Como ya se mostró arribam puede hacer referencia a un objeto por su Datos Name. Pero también puedes usar su Datos Label. En el caso de un Datos Label, debe estar encerrado en doble símbolos << y >>, como <<Label>>.

Puede referenciar cualquier propiedad de un objeto. Por ejemplo, para referenciar la altura de un Cilindro puede usar Cylinder.Height o <<Label_of_cylinder>>.Height.

Para más información de como referenciar objetos, vea Referencia a los datos CAD.

Inicio

Constantes soportadas

Las siguientes constantes están soportadas.

Constant Description
e Número de Euler
pi Pi

Inicio

Operadores soportados

Los siguientes operadores son soportados.

Operator Description
+ Suma
- Resta
* Multiplicación
/ Division de punto flotante
% Residuo
^ Potenciación

Inicio

Funciones soportadas

Funciones matemáticas generales

Las siguientes funciones matemáticas son soportadas:

Funciones trigonométricas

Las Funciones trigonométricas utilizan el grado sexagesimal como unidad predeterminada. Para radianes, agregue rad después del primer valor de una expresión. Entonces, por ejemplo, cos(45) es lo mismo que cos(pi rad / 4). Las expresiones en grados pueden usar deg o °, por ejemplo, 360deg - atan2(3; 4) o 360° - atan2(3; 4). Si una expresión no tiene unidades y debe convertirse a grados o radianes para garantizar la compatibilidad, multiplíquela por 1deg, o 1rad como apropiado, por ejemplo, (360 - X) * 1deg; (360 - X) * 1°; (0,5 + pi / 2) * 1rad.

Function Description Input range
acos(x) Arc cosine -1 <= x <= 1
asin(x) Arc sine -1 <= x <= 1
atan(x) Arc tangent, return value in the range -90° < value < 90° all
atan2(y; x) Arc tangent of y/x accounting for quadrant, return value in the range -180° < value <= 180° all, the invalid input x = y = 0 returns 0
cos(x) Cosine all
cosh(x) Hyperbolic cosine all
sin(x) Sine all
sinh(x) Hyperbolic sine all
tan(x) Tangent all, except x = n*90 with n = odd integer
tanh(x) Hyperbolic tangent all
hypot(x; y) Pythagorean addition (hypotenuse), e.g. hypot(4; 3) = 5 x and y >= 0
cath(x; y) Given hypotenuse, and one side, returns other side of triangle, e.g. cath(5; 3) = 4 x >= y >= 0

Funciones exponenciales y logarítmicas

Function Description Input range
exp(x) Exponential function all
log(x) Natural logarithm x > 0
log10(x) Common logarithm x > 0
pow(x; y) Exponentiation all
sqrt(x) Square root x >= 0
cbrt(x) introduced in version 0.21 Cubic root all

Funciones de redondeo, truncamiento y resto.

Function Description Input range
abs(x) Absolute value all
ceil(x) Ceiling function, smallest integer value greater than or equal to x all
floor(x) Floor function, largest integer value less than or equal to x all
mod(x; y) Remainder after dividing x by y, sign of result is that of the dividend. all, except y = 0
round(x) Rounding to the nearest integer all
trunc(x) Truncation to the nearest integer in the direction of zero all

Inicio

Funciones estadísticas/agregadas

Aggregate functions take one or more arguments.

Individual arguments to aggregate functions may consist of ranges of cells. A range of cells is expressed as two cell references separated by a colon :, for example average(B1:B8) or sum(A1:A4; B1:B4). The cell references may also use cell aliases, for example average(StartTemp:EndTemp).

Las siguientes funciones agregadas son soportadas:

Function Description Input range
average(a; b; c; ...) Average value of the arguments, same as sum(a; b; c; ...) / count(a; b; c; ...) all
count(a; b; c; ...) Count of the arguments, typically used for cell ranges all
max(a; b; c; ...) Maximum value of the arguments all
min(a; b; c; ...) Minimum value of the arguments all
stddev(a; b; c; ...) Standard deviation of the values of the arguments all
sum(a; b; c; ...) Sum of the values of the arguments, typically used for cell ranges all

Inicio

Manipulación de cadenas

Identificación de cadena

Las cadenas se identifican en las expresiones rodeándolas con comillas angulares dobles de apertura/cierre (al igual que las etiquetas).

En el siguiente ejemplo, "TEXTO" se reconoce como una cadena: <<TEXTO>>

Concatenación de cadenas

Las cadenas se pueden concatenar usando el signo '+'.

El siguiente ejemplo <<MI>> + <<TEXTO>> se concatenará con "MITEXTO".

Conversión de cadenas

Los valores numéricos se pueden convertir en cadenas con la función str:

str(Box.Length.Value)

Formato de cadena

El formato de cadena se admite utilizando el estilo (antiguo) % de Python.

Todos los especificadores % tal como se definen en la documentación de Python.

Como ejemplo, supongamos que tiene un cubo predeterminado de 10 mm de lado llamado 'Box' (nombramiento predeterminado de FreeCAD), la siguiente expresión <<Longitud del cubo: %s>> % Box.Length se expandirá a "Longitud del cubo: 10.0 mm"

Para más de un especificador % utilice la siguiente sintaxis: <<La longitud del cubo es %s y el ancho es %s>> % tuple(Box.Length; Box.Width). O use concatenación: <<La longitud del cubo es %s>> % Box.Length + << y el ancho es %s>> % Box.Width. Ambos se expandirán a "La longitud del cubo es de 10.0 mm y el ancho es de 10.0 mm".

Está disponible un archivo de muestra de FreeCAD que utiliza formato de cadena en el foro

Inicio

Funciones de creación de objetos

Los siguientes objetos se pueden crear en expresiones utilizando las siguientes funciones:

Type Function Description
Tuple tuple(a; b; ...) Example: tuple(2; 1; 2)
List list(a; b; ...) Example: list(2; 1; 2)
Vector vector(x; y; z) Create a vector using three unit-less or Length unit values.

Example: vector(2; 1; 3)

create(<<vector>>; x; y; z)
Matrix
matrix(
  a11; a12; a13; a14;
  a21; a22; a23; a24;
  a31; a32; a33; a34;
  a41; a42; a43; a44
)
Create a 4x4 matrix in row-major order:

Se puede proporcionar un mínimo de 1 argumento, como matrix(1), que crea una matriz de identidad.

Example: matrix(1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16)

create(<<matrix>>; a11; a12; ...; a44)
Rotation rotation(axis; angle) Create a Rotation by specifying its axis (Vector) and angle (Angle unit or unit-less), or three Euler angles α, β, γ.

Examples:

  • rotation(vector(0; 1; 0); 45)
  • create(<<rotation>>; 30; 30; 30)
rotation(α; β; γ)
create(<<rotation>>; axis; angle)
create(<<rotation>>; α; β; γ)
Placement placement(base; rotation) Create a Placement with various parameters, including:
  • base: base location (Vector)
  • center: center location (Vector)
  • rotation: Rotation
  • axis: Rotation axis (Vector)
  • angle: Rotation angle (unit-less or Angle unit value)
  • matrix: Matrix

Examples:

  • placement(vector(2; 1; 3); rotation(vector(0; 0; 1); 45))
  • create(<<placement>>; create(<<vector>>; 2; 1; 2); create(<<rotation>>; create(<<vector>>; 0; 1; 0); 45))
placement(base; rotation; center)
placement(base; axis; angle)
placement(matrix)
create(<<placement>>; ...)

Inicio

Funciones vectoriales

Function / Operator Description
v1 + v2 Add two vectors.
v1 - v2 Subtract two vectors.
v * s Uniformly scale a vector by s.
vangle(v1; v2) Angle between two vectors in degrees.
vcross(v1; v2) Cross product of two vectors .
v1 * v2 Dot product of two vectors .
vdot(v1; v2)
vlinedist(v1; v2; v3) Distance between vector v1 and a line through v2 in direction v3.
vlinesegdist(v1; v2; v3) Distance between vector v1 and the closest point on a line segment from v2 to v3.
vlineproj(v1; v2; v3) Project vector v1 on a line through v2 in direction v3.
vnormalize(v) Normalize a vector to a unit vector.
vplanedist(v1) Distance between vector v1 and a plane defined by a point v2 and a normal v3.
vplaneproj(v1) Project vector v1 on a plane defined by a point v2 and a normal v3.
vscale(v; sx; sy; sz) Non-uniformly scale a vector by sx in the X direction, sy in the Y direction, and sz in the Z direction.
vscalex(v; sx)
vscaley(v; sy)
vscalez(v; sz)

Inicio

Funciones matriciales

Rotation and Placement can each be represented by a Matrix. The following functions all take in a Matrix, Rotation, or Placement as their first parameter denoted in the table below by m. The type of the returned object is the same as the object supplied in the first argument except when using mtranslate on a Rotation, in which case a Placement will be returned.

Function Description
minvert(m) Calculate the Inverse matrix.
mrotate(m; rotation) Rotate by either:
  • a Rotation
  • an axis (Vector) and an angle (Angle unit or unit-less)
  • three Euler angles α, β, γ
mrotate(m; axis; angle)
mrotate(m; α; β; γ)
mrotatex(m; angle) Rotate around the X axis.
mrotatey(m; angle) Rotate around the Y axis.
mrotatez(m; angle) Rotate around the Z axis.
mtranslate(m; vector) Translate by a vector (Vector) or X, Y, Z values. If a Rotation is translated, the returned object is a Placement.
mtranslate(m; x; y; z)
mscale(m; vector) Scale by a vector (Vector) or X, Y, Z values.
mscale(m; x; y; z)

Inicio

Expresiones condicionales

Conditional expressions are of the form condition ? resultTrue : resultFalse. The condition is defined as an expression that evaluates to either 0 (false) or non-zero (true).

The following relational operators are defined:

Unit Description
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to

Inicio

Unidades

Las unidades se pueden utilizar directamente en expresiones. El analizador los conecta con el valor anterior. Entonces 2mm o 2 mm es válido mientras que mm no es válido porque no hay un valor anterior.

All values must have a unit. Therefore you must in general use a unit for values in spreadsheets.
In some cases it works even without a unit, for example if you have e.g. in spreadsheet cell B1 just the number 1.5 and refer to it for a pad height. This only works because the pad height predefines the unit mm that is used if no unit is given. It will nevertheless fail if you use for the pad height e.g. Sketch1.Constraints.Width - Spreadsheet.B1 because Sketch1.Constraints.Width has a unit and Spreadsheet.B1 has not.

Se pueden ingresar directamente unidades con exponentes. Entonces, por ejemplo, mm^3 se reconocerá como mm³ y m^3 se reconocerá como m³.

Si tienes una variable cuyo nombre es el de una unidad debes poner la variable entre << >> para evitar que sea reconocida como una unidad. Por ejemplo, si tiene la dimensión Sketch.Constraints.A, se reconocerá como la unidad amperio. Por lo tanto debes escribirlo en la expresión como Sketch.Constraints.<<A>>.

El analizador de expresiones reconoce las siguientes unidades:

Cantidad de sustancia

Unit Description
mmol Millimole
mol Mole

Ángulo

Unit Description
° Degree; alternative to the unit deg
deg Degree; alternative to the unit °
rad Radian
gon Gradian
S Second of arc; alternative to the unit ″
Second of arc; alternative to the unit S
M Minute of arc; alternative to the unit ′
Minute of arc; alternative to the unit M

Corriente

Unit Description
mA Milliampere
A Ampere
kA Kiloampere
MA Megaampere

Capacitancia electrica

Unit Description
pF Picofarad
nF Nanofarad
uF Microfarad; alternative to the unit µF
µF Microfarad; alternative to the unit uF
mF Millifarad
F Farad; 1 F = 1 s^4·A^2/m^2/kg

Carga eléctrica

Unit Description
C Coulomb; 1 C = 1 A*s

Conductividad eléctrica

Unit Description
uS Microsiemens; alternative to the unit µS
µS Microsiemens; alternative to the unit uS
mS Millisiemens
S Siemens; 1 S = 1 s^3·A^2/kg/m^2
kS KiloSiemens
MS MegaSiemens

Inductancia eléctrica

Unit Description
nH Nanohenry
uH Microhenry; alternative to the unit µH
µH Microhenry; alternative to the unit uH
mH Millihenry
H Henry; 1 H = 1 kg·m^2/s^2/A^2

Potencial eléctrico

Unit Description
mV Millivolt
V Volt
kV Kilovolt

Resistencia electrica

Unit Description
Ohm Ohm; 1 Ohm = 1 kg·m^2/s^3/A^2
kOhm Kiloohm
MOhm Megaohm

Energía/trabajo

Unit Description
mJ Millijoule
J Joule
kJ Kilojoule
eV Electronvolt; 1 eV = 1.602176634e-19 J
keV Kiloelectronvolt
MeV Megaelectronvolt
kWh Kilowatt hour; 1 kWh = 3.6e6 J
Ws Watt second; alternative to the unit Joule
VAs Volt-ampere-second; alternative to the unit Joule
CV Coulomb-volt; alternative to the unit Joule
cal Calorie; 1 cal = 4.184 J
kcal Kilocalorie

Fuerza

Unit Description
mN Millinewton
N Newton
kN Kilonewton
MN Meganewton
lbf Pound of force

Longitud

Unit Description
nm Nanometer
um Micrometer; alternative to the unit µm
µm Micrometer; alternative to the unit um
mm Millimeter
cm Centimeter
dm Decimeter
m Meter
km Kilometer
mil Thousandth of an inch; alternative to the unit thou
thou Thousandth of an inch; alternative to the unit mil
in Inch; alternative to the unit "
" Inch; alternative to the unit in
ft Foot; alternative to the unit '
' Foot; alternative to the unit ft
yd Yard
mi Mile

Intensidad luminosa

Unit Description
cd Candela

Flujo magnético

Unit Description
Wb Weber; 1 Wb = 1 kg*m^2/s^2/A

Densidad de flujo magnético

Unit Description
G Gauss; 1 G = 1 e-4 T
T Tesla; 1 T = 1 kg/s^2/A

Masa

Unit Description
ug Microgram; alternative to the unit µg
µg Microgram; alternative to the unit ug
mg Milligram
g Gram
kg Kilogram
t Tonne
oz Ounce
lb Pound; alternative to the unit lbm
lbm Pound; alternative to the unit lb
st Stone
cwt Hundredweight

Potencia

Unit Description
W Watt
kW Kilowatt

Presión

Unit Description
Pa Pascal
kPa Kilopascal
MPa Megapascal
GPa Gigapascal
uTorr Microtorr; alternative to the unit µTorr
µTorr Microtorr; alternative to the unit uTorr
mTorr Millitorr
Torr Torr; 1 Torr = 133.32 Pa
psi Pound-force per square inch; 1 psi = 6.895 kPa
ksi Kilopound-force per square inch

Temperatura

Unit Description
uK Microkelvin; alternative to the unit µK
µK Microkelvin; alternative to the unit uK
mK Millikelvin
K Kelvin

Tiempo

Unit Description
s Second
min Minute
h Hour
Hz (1/s) Hertz
kHz Kilohertz,
MHz Megahertz
GHz Gigahertz
THz Terahertz

Volumen

Unit Description
ml Milliliter
l Liter
cft Cubicfoot

Unidades imperiales especiales

Unit Description
mph Miles per hour
sqft Square foot

Unidades no compatibles

The following commonly used units are not yet supported, for some an alternative is provided:

Unit Description Alternative
°C Celsius [°C] + 273.15 K
°F Fahrenheit; ([°F] + 459.67) × ​5/9
u Atomic mass unit; alternative to the unit Da 1.66053906660e-27 kg
Da Dalton; alternative to the unit u 1.66053906660e-27 kg
sr Steradian not directly
lm Lumen not directly
lx Lux not directly
px Pixel not directly

Inicio

Caracteres y nombres no válidos

The expression feature is very powerful but to achieve this power it has some limitations concerning some characters. To overcome this, FreeCAD offers to use labels and reference them instead of the object names. In labels you can use almost all special characters.

In cases where you cannot use a label, such as the name of a sketch's constraints, you must be aware what characters are not allowed.

Etiquetas

For labels there are no invalid characters, however some characters need to be escaped:

Characters Description
', \, " Need to be escaped by adding \ in front of them.

For example, the label Sketch\002 must be referenced as <<Sketch\\002>>.

Nombres

Names of objects like dimensions, sketches, etc. may not have the characters or character sequences listed below, otherwise the name is invalid:

Characters / Character sequences Description
+, -, *, /, ^, _, <, >, (, ), {, }, [, ], ., ,, = Characters that are math operators or part of mathematical constructs
A, kA, mA, MA, J, K, ' , ft , °, and many more! Characters and character sequences that are units (see the Units paragraph)
#, !, ?, §, $, %, &, :, ;, \, |, ~, , ¿, and many more! Characters used as placeholder or to trigger special operations
pi, e Mathematical constants
´, `, ' , " Characters used for accents
space A space defines the end of a name and can therefore not be used

For example, the following name is valid: <<Sketch>>.Constraints.T2üßµ@. While these are invalid names: <<Sketch>>.Constraints.test\result_2 (\r means "carriage return") or <<Sketch>>.Constraints.mol (mol is a unit).

Since shorter names (especially if they have only one or two characters) can easily result in invalid names, consider using longer names and/or establishing a suitable naming convention.

Cell aliases

See Spreadsheet SetAlias.

Inicio

Referencia a los datos CAD

It is possible to use data from the model itself in an expression. To reference a property use object_name.property or <<object_label>>.property, labels must be enclosed in << and >>. If you want to use labels they must be unique.

All next examples reference the object by its name, but in all cases the object label can also be used.

If the property is a compound of fields, the individual fields can be accessed as object_name.property.field.

Para referenciar una lista de objetos use object_label.list[list_index]. Si quiere por ejemplo referenciar una restricción de un croquis use Sketch.Constraints[16]. Si está en el mismo croquis puede omitir su nombre y solo usar Constraints[16].Note que el índice inicia en 0, por lo que la restricción 17 tiene que ser referenciada como Constraints[16]

To reference the object itself use the _self pseudo property: object_name._self.

The following table shows some more examples:

CAD data Call in expression Result
Length of a Part Box Box.Length Length with units (mm)
Volume of the Box Box.Shape.Volume Volume in mm³ without units
Shape type of the Box Box.Shape.ShapeType String: Solid
Label of the Box Box.Label String: Label
X-coordinate of center of mass of the Box Box.Shape.CenterOfMass.x X-coordinate in mm without units
X-coordinate of the Box placement Box.Placement.Base.x X-coordinate with units (mm)
X-component of the rotation axis of the Box placement Box.Placement.Rotation.Axis.x X-component of the unit vector in mm without units
Rotation angle of the Box placement Box.Placement.Rotation.Angle Rotation angle with units (deg)
Full Box object Box._self Object of type <Part::PartFeature>
Value of constraint in a sketch Constraints.Width Numeric value of the named constraint Width in the sketch, if the expression is used in the sketch itself.
Value of constraint in a sketch MySketch.Constraints.Width Numeric value of the named constraint Width in the sketch, if the expression is used outside of the sketch.
Value of a spreadsheet alias Spreadsheet.Depth Value of the alias Depth in the spreadsheet Spreadsheet
Value of a local property Length Value of the DatosLength property in e.g a Pad object, if the expression is used in e.g DatosLength2 in the same object.

Cyclic dependencies

FreeCAD checks dependencies based on the relationship between document objects, not properties. This means that you cannot provide data to an object and query that same object for results. For example, even though there are no cyclic dependencies when the properties themselves are considered, you may not have an object which gets its dimensions from a spreadsheet and then display the volume of that object in the same spreadsheet. You have to use two spreadsheets, one to drive your model and the other for reporting.

As a workaround it is possible to display a cell range from the second spreadsheet in the first (or vice versa) by creating a cell binding with the Hide dependency of binding option.

Another way to workaround cyclic dependencies is to hide the reference by using the href or hiddenref function for individual expressions, for example: href(Box.Length).

Please note that both mentioned workarounds should be used with caution, and that they do not work if the properties that are reported depend on dimensions that are driven from the same spreadsheet.

Inicio

Variables globales de todo el documento

There is no concept of global variables in FreeCAD at the moment. Instead, arbitrary variables can be defined as cells in a spreadsheet using the Spreadsheet workbench, and then be given a name using the alias property for the cell (right-click on cell). Then they can be accessed from any expression just as any other object property.

Inicio

Enlace entre documentos

It is possible (with limitations) to define a Property of an object in your current document (".FCstd" file) by using an Expression to reference a Property of an object contained in a different document (".FCstd" file). For example, a cell in a spreadsheet or the DatosLength of a Part Cube, etc. in one document can be defined by an Expression that references the X Placement value or another Property of an object contained in a different document.

A document's name is used to reference it from other documents. When saving a document the first time, you choose a file name; this is usually different from the initial default "Unnamed1" (or its translated equivalent). To prevent links being lost when the master document is renamed upon saving, it is recommended that you first create the master document, create a spreadsheet inside it, and save it. Subsequently, you can still make changes to the file and its spreadsheet but you should not rename it.

Once the master document with the spreadsheet is created and saved (named), it is safe to create dependent documents. For example, assuming you name the master document master, the spreadsheet modelConstants, and give a cell an alias-name Length, you can then access the value as:

master#modelConstants.Length

Note that the master document must be loaded for the values in the master to be available to the dependent document.

Of course, it's up to you to load the corresponding documents later when you want to change anything.

Inicio

Problemas conocidos / tareas pendientes

  • FreeCAD does not yet have a built-in expression manager where all expressions in a document are listed, and can be created, deleted, queried, etc. But an addon is available: fcxref expression manager.
  • Open bugs/tickets for Expressions can be found on GitHub.

Inicio