Skip to main content
CNC.wiki

Arithmetic Functions in CNC Macros: SIN, COS, and SQRT Guide

Master arithmetic functions like SIN, COS, and SQRT in Fanuc, Siemens, and Mitsubishi CNC macros to calculate parametric toolpaths and prevent FPU errors.

Hakan Gündoğdu
Hakan Gündoğdu

CNC CARE Co-founder

Introduction to Macro Arithmetic Functions

A tool crashing violently into a rigid vise jaw, workpiece clamp, or the machine spindle at rapid traverse is the severe physical consequence of un-normalized floating-point calculations or out-of-sync LookAhead buffering in CNC macros. When programs rely on mathematical functions like SIN, COS, or SQRT to calculate dynamic coordinates on the fly, microscopic rounding errors—often called floating-point dust—can accumulate. If a controller attempts to parse these faulty variables to execute the next position, the tool can deviate from its intended path, resulting in an uncommanded travel jump that destroys the workpiece and damages machine mechanics. Restricting these mathematical operations to strictly sanitized ranges and implementing proper synchronization command stops is crucial to avoiding catastrophic hard collisions on the shop floor.

Technical Summary of Mathematical Commands

AttributeDetail
Command CodesSIN, COS, SQRT, SQR, POT, POW
Modal GroupMathematical / Arithmetic Macro Functions (Non-modal)
Supported BrandsFanuc, Siemens, Mitsubishi
Critical ParametersFanuc: 6004#1 (MFZ), 6004#0 (NAT), 6008#0 (F16); Siemens: R0 to R299; Mitsubishi: #1273 (ASIN output range), #1259 (macro priority)
Main ConstraintsAngles must be in degrees; division by zero and TAN[90.0] are forbidden; nesting is limited to 5 levels on Fanuc and Mitsubishi.

Quick Read: Key Takeaways for Operators

  • Enclose arguments for mathematical functions in square brackets [] on Fanuc and Mitsubishi, and round brackets () on Siemens.
  • Ensure all trigonometric inputs (SIN, COS, TAN) are specified strictly in degrees, as radians will cause flawed calculations.
  • Sanitize variable values using logical checks before passing them to a SQRT function to prevent negative-base calculations.
  • Program a preprocessing stop (STOPRE) on Siemens controls to freeze LookAhead decoding before referencing calculated variables.
  • Observe nesting limitations by keeping brackets to a maximum of 5 levels on Fanuc and Mitsubishi to avoid buffer overflows.
  • Use parameters like Fanuc 6004#0 or Mitsubishi #1273 to globally shift quadrant ranges for inverse trigonometric results.

Basic Concepts of Trigonometric Functions

Custom macro engines allow CNC controllers to perform complex trigonometric and arithmetic operations in real-time. By utilizing functions like SIN, COS, and SQRT, developers can construct parametric master programs that calculate toolpaths dynamically at the machine. This capability eliminates the need to output thousands of fixed coordinates from external CAD/CAM software for minor design variations. Instead, parameters like diameters, angle increments, or depths are passed directly into the macro, allowing the machine to compute its own coordinate vectors.

When programming custom macros using g65-custom-macro-b, math functions are often paired with macro-logical-operators to perform safety checks. Proper parameter mapping is also required during g65-macro-argument-assignment to ensure mathematical variables are correctly populated.

However, trigonometric math can produce minor mathematical anomalies instead of exact values, which are referred to as floating-point dust. If these microscopic rounding errors are not managed, consecutive calculations can accumulate coordinate drift over time. A CNC control that executes positioning moves based on un-normalized variables risks driving the tool off-path. To prevent this coordinate drift, programmers must implement mathematical sanitization and error-checking logic to ensure all variables fall within safe bounds before executing travel commands.

Command Structure and Priority

Arithmetic macro commands follow a structured syntax where the evaluated mathematical result is assigned directly to a local, common, or system variable. For Fanuc and Mitsubishi controls, this syntax is executed as a variable assignment using square brackets to enclose the arguments of the trigonometric or square root functions. Siemens takes a different approach by integrating mathematical syntax directly into its high-level NC programming language, allowing variables to be evaluated using standard parenthesis notation.

The priority of operations on all three platforms follows standard mathematical conventions. Functions are evaluated first, followed by multiplication and division, and finally addition and subtraction. Brackets or parentheses must be used to override this default sequence and define explicit calculation paths. If a programmer neglects to bracket multi-step formulas, the controller will process the arithmetic sequentially, which can drastically alter the final coordinate output.

Standard syntax formats for each brand:

  • Fanuc: #i = SIN[#j], #i = COS[#j], #i = SQRT[#j] or #i = SQR[#j]
  • Siemens: R_var = SIN(x), R_var = COS(x), R_var = SQRT(x), R_var = POT(x), R_var = ATAN2(y, x)
  • Mitsubishi: #i = SIN[#j], #i = COS[#j], #i = SQRT[#j] or #i = SQR[#j], #i = POW[#j, #k]

Critical math control parameters across systems:

BrandParameterDescriptionValid Settings
Fanuc6004#1 (MFZ)Handles microscopic trigonometric results underflow.0 = Underflow; 1 = Normalize to 0
Fanuc6004#0 (NAT)Dictates the inverse trigonometric output domain.0 = 0° to 360.0°; 1 = -180.0° to 180.0°
Fanuc6008#0 (F16)Controls legacy calculation precision compatibility.0 = New; 1 = FS16i / FS0i-C compatible
SiemensR0 to R299Predefined arithmetic parameters (floating-point format).±0.0000001 to 99999999
Mitsubishi#1273 (ext09/bit0)Shifts the output range of inverse sine (ASIN).0 = -90° to 90°; 1 = 270° to 90°
Mitsubishi#1259 (set31/bit7)Determines internal macro priority and processing speed.Custom bit settings

Brand Applications: Controller Specific Implementations

Fanuc

Fanuc controls manage mathematical precision and underflow using parameters 6004#1 and 6004#0. The parameter 6004#1 controls whether infinitesimal calculations are normalized to zero, while 6004#0 shifts the output domain of inverse trigonometric functions.

Arithmetic variables are assigned using square brackets to evaluate expressions:

; Fanuc examples:
#100 = SQRT[#1 * #1 + #2 * #2] ; Calculate hypotenuse
#101 = SIN[45.0] * 50.0       ; Determine sine component
#102 = #101 + COS[#3]         ; Sum with cosine component
  • Parameters: 6004#1 (MFZ) normalizes underflow math; 6004#0 (NAT) switches ATAN/ASIN domains; 6008#0 (F16) forces compatibility modes.
  • Alarms: Alarm 119 (Illegal Argument for negative SQRT), Alarm 112 (Divided by Zero or TAN[90]), Alarm 118 (Parenthesis Nesting Error), Alarm 111 (Calculated Data Overflow).
  • Version Differences: Standard macros use standard commands. PMC Ladder/Structured Text uses typed function blocks: single-precision (16 bytes) uses SINR, COSR, SQRTR; double-precision (20/28 bytes) uses SINL, COSL, SQRTL.

Warning: Exceeding five levels of bracket nesting [] in a single command line will immediately trigger Alarm 118, halting the machine execution buffer.

Siemens

Siemens Sinumerik controls utilize predefined variables R0 through R299 to store calculated arithmetic values. The floating-point values are stored internally using standard 64-bit IEEE formats, which are susceptible to precision drift during exact logic comparisons.

Formulas can be calculated and stored using round brackets, or integrated directly inside motion blocks:

; Siemens examples:
R40 = ATAN2(30.5, 80.1)       ; Calculate quadrant-aware arctangent
R15 = SQRT(R1 * R1 + R2 * R2) ; Calculate hypotenuse
STOPRE                        ; Preprocessing stop command
N40 G1 Z=SIN(25.3)-R5 F200    ; Direct inline trigonometric travel
  • Parameters: R parameters (R0 to R299) store floating-point numbers. Custom real variables are defined using DEF REAL.
  • Alarms: Alarm 1019 (Floating point arithmetic error / FPU exception), Alarm 1020 (Floating point arithmetic error in compile cycle).
  • Version Differences: Entry-level SINUMERIK 808D allocates exactly 300 R parameters. Advanced models like 840D sl and SINUMERIK ONE support expansive dynamic variable arrays and complex multi-axis orientation transformations.

Warning: Failing to command a preprocessing stop (STOPRE) before relying on a calculated mathematical value can cause LookAhead mismatch and lead to severe tool crashes.

Mitsubishi

Mitsubishi macro programming manages trigonometric output domains and priority settings via parameters #1273 and #1259. Parameter #1273 determines the calculation range of the inverse sine function, while #1259 optimizes execution speed.

Trigonometric values are evaluated using square brackets and assigned to variables:

; Mitsubishi examples:
#501 = SIN[14]                                              ; Assign sine of 14 degrees
#573 = SQRT[10. * 10. + 20. * 20.]                         ; Calculate hypotenuse
#101 = SQRT[[#111 - #112] * SIN[[#113 + #114] * #115]]      ; Complex nested trigonometry
#107 = POW[2.5, 3.5]                                        ; Power calculation (M8 series only)
  • Parameters: Parameter #1273 switches ASIN output range; Parameter #1259 configures internal processing method and macro calculation priority.
  • Alarms: Program Error P282 (Arithmetic failure / negative SQRT), Program Error P225 (Format error / unclosed bracket), Program Error P241 (Negative variable reference).
  • Version/Series Differences: Exponents via POW function require the M8 series. Extended Common Variable III files store on SD cards inside the control unit for M800VW/M80VW, but in the display unit for M800VS/M80V.

Warning: Inserting mathematical operators directly into axis letters (such as X123+0) shifts the interpreted coordinate decimal point, causing millimeter vs micron reading errors.

Brand Comparison: Fanuc, Siemens, and Mitsubishi

Feature / TopicFanucSiemensMitsubishi
Argument Bracket SyntaxSquare brackets [] (e.g., SIN[45.0])Round brackets () (e.g., SIN(45.0))Square brackets [] (e.g., SIN[45.0])
Formula Nesting LimitMax 5 levels of bracket nesting ([])Prioritized by round brackets (), no strict low nesting limitMax 5 levels of bracket nesting ([])
Inverse Trigonometry Range ShiftsParameter 6004#0 shifts ATAN range from 0-360.0° to -180.0° to 180.0°ATAN2(,) natively returns vector angle in all four quadrants (-180° to 180°)Parameter #1273 shifts ASIN range from -90° to 90° to 270° to 90°
Floating Point Precision AnomaliesParameter 6004#1 (MFZ) normalizes calculations <= 1.0*10^-8 to 0Native TRUNC() command truncates floating-point REAL precision drift before logic comparisonsParameter #1259 sets priority and processing speed for macro evaluation
Power / Exponent FunctionsStandard macro multiplication; EXP for natural exponentPredefined POT(x) (square) or custom exponent powersNative POW[base, exponent] (M8 series only)
Inline Motion CalculationsNot supported (must assign to variables first)Fully supported (math expressions inline within travel blocks e.g. Z=SIN(25.3))Not supported (must assign to variables first)

Technical Analysis of Controller Behavior

Analyzing the arithmetic engines of Fanuc, Siemens, and Mitsubishi reveals distinct differences in syntax integration, precision management, and preprocessor buffering. Fanuc and Mitsubishi utilize a classic macro design where mathematical operations are calculated in isolated blocks and then stored into system or user variables. This structure isolates calculations from axis movement, protecting the motion parser but requiring extra code lines. Siemens, by contrast, integrates advanced math directly into its NC kernel, allowing inline calculations inside travel blocks. This allows developers to combine trigonometry and linear motion in a single line, reducing processing overhead and increasing program readability.

Precision management also differs across the three brands. Fanuc addresses floating-point noise through parameter 6004#1, which normalizes underflow values directly to zero to prevent path drift. Siemens solves floating-point drift in its 64-bit IEEE variables using the native TRUNC() function, allowing programmers to strip decimal noise before executing coordinate logic comparisons. For inverse trigonometry, Fanuc uses parameter 6004#0 to shift ATAN quadrants, and Mitsubishi uses parameter #1273 to rotate the ASIN output. Siemens bypasses these parameters entirely by using the ATAN2(,) command to resolve vector angles across all four quadrants.

Finally, execution synchronization represents a major architectural difference. While Fanuc and Mitsubishi process macros sequentially and halt on errors, Siemens' active LookAhead buffer can decode mathematical blocks far in advance of physical tool movements. If the Siemens buffer parses a dynamic geometry variable before it has been finalized by active cycles, a mismatch occurs. To maintain path integrity, Siemens requires programmers to command a STOPRE preprocessing stop to synchronize the buffer, a constraint that does not exist in the same way on Fanuc or Mitsubishi controls.

Program Examples and Code Blocks

Fanuc Example

#100 = SQRT[#1 * #1 + #2 * #2] ; Calculate hypotenuse of triangle
#101 = SIN[45.0] * 50.0       ; Calculate sine offset component
#102 = #101 + COS[#3]         ; Combine with cosine component

dry run

  • Block 1: The controller calculates the square root of the sum of the squares of variables #1 and #2, assigning the result to variable #100. If #1 or #2 results in a negative sum, or if the argument is negative, the CNC will trigger Alarm 119.
  • Block 2: The sine of 45.0 degrees is calculated and multiplied by 50.0. The result is assigned to variable #101.
  • Block 3: The cosine of variable #3 (evaluated in degrees) is calculated and added to the value in #101. The final sum is stored in variable #102.

Siemens Example

R40 = ATAN2(30.5, 80.1)       ; Calculate quadrant-aware arctangent
R15 = SQRT(R1 * R1 + R2 * R2) ; Calculate hypotenuse of triangle
STOPRE                        ; Halt preprocessing buffer
N40 G1 Z=SIN(25.3)-R5 F200    ; Move Z-axis using inline math
R14 = R1 * R2 + R3            ; Priority: multiply R1 by R2, then add R3

dry run

  • Block 1: The ATAN2 function calculates the angle of the vector formed by coordinates 30.5 (Y) and 80.1 (X), resolving the exact quadrant between -180 and +180 degrees and storing it in parameter R40.
  • Block 2: The controller calculates the square root of the sum of the squares of parameters R1 and R2, storing the result in parameter R15.
  • Block 3: The STOPRE command halts the LookAhead preprocessor buffer, forcing the CNC to wait until all prior arithmetic is fully evaluated before reading the next block.
  • Block 4: The controller executes a linear move along the Z-axis to a position calculated by subtracting the value of parameter R5 from the sine of 25.3 degrees, at a feedrate of 200 mm/min.
  • Block 5: The controller multiplies R1 by R2 first (due to standard operator priority), then adds R3, storing the result in parameter R14.

Mitsubishi Example

#501 = SIN[14]                                              ; Evaluate sine of 14 degrees
#573 = SQRT[10. * 10. + 20. * 20.]                         ; Calculate hypotenuse
#101 = SQRT[[#111 - #112] * SIN[[#113 + #114] * #115]]      ; Complex nested equation
#107 = POW[2.5, 3.5]                                        ; Raise 2.5 to power of 3.5

dry run

  • Block 1: The sine of 14 degrees is calculated and stored in variable #501.
  • Block 2: The controller calculates the square root of the sum of the squares of 10.0 and 20.0, assigning the result to variable #573.
  • Block 3: The controller evaluates the nested brackets starting from the innermost: adds #113 and #114, multiplies by #115, takes the sine, multiplies by the difference of #111 and #112, and finally calculates the square root, storing the result in #101. Up to 5 nesting levels are supported.
  • Block 4: The value 2.5 is raised to the power of 3.5 using the M8 series-exclusive POW function, with the result assigned to variable #107.

Error Analysis and Troubleshooting

Alarm CodeTriggerOperator SymptomRoot Cause / Fix
Fanuc Alarm 119A negative argument is specified inside a SQRT function, or a BCD argument is negative.Axis movement freezes, and the screen displays "119 ILLEGAL ARGUMENT", halting execution.Root Cause: Input variable evaluated to a negative number.
Fix: Sanitize the variable before the calculation using an IF logic statement to ensure the base is >= 0.
Fanuc Alarm 112A division by zero is attempted, or a tangent operation is commanded at exactly 90 degrees (TAN[90.0]).The machine stops mid-cycle, throwing "112 DIVIDED BY ZERO" on the operator console.Root Cause: A variable denominator resolved to zero, or TAN was executed at 90.0°.
Fix: Insert conditional check to verify denominator is not zero and angle is not 90.0° before processing.
Fanuc Alarm 118Bracket nesting inside a Custom Macro B mathematical formula exceeds five levels.Program execution fails instantly on the offending block, displaying "118 PARENTHESIS NESTING ERROR".Root Cause: Formula utilizes more than 5 nested bracket pairs ([]).
Fix: Simplify the equation by splitting the calculation across multiple lines using intermediate variables.
Siemens Alarm 1019The processor's FPU triggers an exception due to a fatal computational error (e.g., negative SQRT argument or zero division).Execution halts, throwing "Alarm 1019: Floating point arithmetic error", and the NC channel requires a reset.Root Cause: A mathematical impossibility was evaluated during runtime.
Fix: Check the log files (retrieved with <Ctrl>+<Alt>+<D>) and insert check statements to prevent negative square root inputs or zero division.
Mitsubishi P282An arithmetic operation fails mathematically, such as passing a negative value to SQRT or dividing by zero.The CNC immediately stops, flashing "Program Error (P282)" on the screen.Root Cause: Math violation during macro execution (negative square root base or division by zero).
Fix: Validate input parameters using range checks to ensure values are within valid mathematical limits.
Mitsubishi P225A linefeed is inserted in a macro block without closing a bracket ], or an invalid character is found within brackets.The parser rejects the block, throwing "Program Error (P225)" and preventing cycle start.Root Cause: Syntax error or missing closing bracket.
Fix: Verify bracket balancing and ensure every opening [ has a matching closing ].

Application Note: Buffer Management and Precision

An uncommanded rapid traverse deviation that drives a tool spindle or turret directly into a chuck, tailstock, compensating chuck, or workpiece clamp—resulting in a catastrophic hard collision and immediate scrap part—is the ultimate consequence of neglecting preprocessor sync stops like STOPRE on Siemens or failing to normalize floating-point dust on Fanuc/Mitsubishi. When executing dynamic calculations, trigonometric math produces microscopic floating-point dust rather than perfect zeros. If this un-normalized data is used directly in a travel command without validation or without halting the LookAhead buffer, the controller calculates coordinates using outdated or empty data. To prevent these collisions, programmers must sanitize all variables with logical IF routines prior to mathematical execution and visually confirm paths using the Graphic Check utility.

Related Command Network

  • TAN / ATAN2: Used alongside SIN and COS to resolve angular calculations and quadrant positions.
  • ABS: Evaluates the absolute value of an expression to prevent passing negative numbers to the SQRT function.
  • ROUND / TRUNC: Corrects floating-point precision anomalies and decimal drift before making exact logic comparisons.
  • STOPRE: Forces a Siemens preprocessor stop to synchronize dynamic mathematical variables with active axis motion.
  • POW / POT: Enables native exponential power calculations on supported controller architectures.

Conclusion and Best Practices

Maintaining rigorous mathematical hygiene is mandatory when implementing arithmetic functions in CNC macros. Programmers must sanitize variable inputs using range checks before passing them to square root or division functions, implement LookAhead synchronization commands on controllers with active preprocessors, and configure underflow parameters to neutralize floating-point dust. These precautions ensure that dynamic calculations produce precise, reliable coordinate movements rather than catastrophic machine crashes.

Frequently Asked Questions

How do I prevent math overflow alarms when nesting multiple macro equations?

To prevent buffer overflows and parenthetical nesting alarms, split complex equations into multiple lines using intermediate variables. While Fanuc and Mitsubishi strictly enforce a limit of five nesting levels for square brackets, breaking down the formulas ensures the parser can process each step sequentially and allows you to easily debug intermediate values.

Why does my CNC trigger an illegal argument alarm during square root calculations?

An illegal argument alarm (such as Fanuc Alarm 119 or Mitsubishi P282) is triggered because the square root function is commanded with a negative base value. To resolve this, insert a conditional check using macro logical operators to verify the variable is greater than or equal to zero before executing the SQRT function, defaulting the value or halting the program if it falls out of range.

Why do exact logic comparisons on macro calculations sometimes fail even when the numbers look identical?

Exact logic comparisons fail due to microscopic decimal drift, known as floating-point dust, which occurs because trigonometric calculations in 64-bit IEEE formats produce tiny remainders instead of perfect integers. To prevent this, apply precision correction functions like TRUNC() on Siemens or adjust underflow parameters like 6004#1 on Fanuc to normalize values before executing logical IF comparisons.

Still not resolved?

Ask our AI assistant about this topic in natural language. Grounded in verified sources, no hallucinations.

Ask AI Assistant
Hakan Gündoğdu
Hakan Gündoğdu
  • CNC CARE Co-Founder (May 2025 - Present)
  • Mitsubishi Electric NC Sales & Service Section Manager (2008 - 2025)
  • Reis CNC Service Engineer (2003 - 2005)
  • Ören Kalıp CNC Mold Line Team Leader (1999 - 2002)

With over 25 years of experience working in all areas of the CNC machine industry, I continue my activities as a co-founder of CNC CARE, where we offer brand-independent consulting, engineering, and original spare parts services.

Related Articles

Other articles on this topic