Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for cosine_int.bat

(view source code of cosine_int.bat as plain text)

  1. @ECHO OFF
  2. :: A not-too-serious attempt to calculate cosines using native batch
  3. :: commands only by Rob van der Woude, http://www.robvanderwoude.com
  4.  
  5. :: Usage:  COSINE.BAT  angle
  6.  
  7. :: Angle must be specified in radians
  8.  
  9. :: Accuracy deteriorates fast with larger angles
  10.  
  11. :: cos(x) = 1 - x2/2! + x4/4! - x6/g! + x8/8! - ...
  12. :: cos(x) = 1 - x2/2! + (x2/2!)*x2/(3*4) - (x4/4!)*x2/(5*6) + (x6/6!)*x2/(7*8) - ...
  13. :: 100 * cos(x) = 100 - (100)*((100x)2/(100)2)/2! + (100*((100x)2/(100)2)/2!)*(100x)2/(3*4*(100)2) - ...
  14.  
  15.  
  16. SETLOCAL ENABLEDELAYEDEXPANSION
  17.  
  18. :: pi/4 = 0,78539816339744830961566084581988
  19. SET X=0.78539816339744830961566084581988
  20. IF NOT "%~1"=="" SET X=%~1
  21.  
  22. :: The following sector converts the floating point value to
  23. :: an integer of 10000 times its value (correctly rounded);
  24. :: a lot of work to compensate for the lack of floating point
  25. :: math in batch
  26.  
  27. :: Accuracy specifies how many digits will be used
  28. SET Accuracy=3
  29. SET Factor0=1
  30. FOR /L %%A IN (1,1,%Accuracy%) DO SET /A Factor0 *= 10
  31.  
  32. ECHO.%x% | FIND "." >NUL
  33. IF ERRORLEVEL 1 (
  34. 	SET /A  NewX = !X:~0,%Accuracy%! * %Factor0%
  35. ) ELSE (
  36. 	SET DotPos=
  37. 	SET /A NewDotPos = 10 + %Accuracy% + 1
  38. 	SET X=%X%000000000000
  39. 	FOR /L %%A IN (0,1,10) DO (
  40. 		IF NOT DEFINED DotPos (
  41. 			IF "!X:~%%A,1!"=="." (
  42. 				SET DotPos=%%A
  43. 			)
  44. 		)
  45. 	)
  46. 	SET /A NewDotPos = !DotPos! + %Accuracy% + 2
  47. )
  48. IF DEFINED NewDotPos (
  49. 	SET NewX=!X:~0,%NewDotPos%!
  50. 	SET NewX=!NewX:.=!
  51. 	SET /A NewX = "( 1!NewX! + 5 - ( 100 * %Factor0% ) ) / 10"
  52. )
  53.  
  54. SET Cosine=%Factor0%
  55. SET PrevFactor=%Factor0%
  56. SET Sign=1
  57. SET /A NewX2 = %NewX% * %NewX%
  58.  
  59. FOR /L %%A IN (2,2,12) DO (
  60. 	SET /A Sign *= -1
  61. 	IF !PrevFactor! LEQ 0 (
  62. 		SET PrevFactor=0
  63. 		SET Factor%%A=
  64. 	) ELSE (
  65. 		SET /A Factor%%A = "( !PrevFactor! * !NewX2! / %Factor0% ) / ( ( %%A - 1 ) * %%A * %Factor0% )"
  66. 		IF !Factor%%A! LEQ 0 (
  67. 			SET PrevFactor=0
  68. 			SET Factor%%A=
  69. 		) ELSE (
  70. 			SET /A Cosine = "!Cosine! + !Sign! * !Factor%%A!"
  71. 			SET PrevFactor=!Factor%%A!
  72. 		)
  73. 	)
  74. )
  75.  
  76. IF %Cosine% LSS %Factor0% (
  77. 	SET Cosine=0000%Cosine%
  78. 	SET Cosine=0.!Cosine:~-%Accuracy%!
  79. ) ELSE (
  80. 	SET Cosine=1
  81. )
  82.  
  83. ECHO cos^(%~1^)=%Cosine%
  84.  
  85. ENDLOCAL
  86.  

page last modified: 2024-04-16; loaded in 0.0057 seconds