math.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /**
  2. * @license
  3. * Visual Blocks Language
  4. *
  5. * Copyright 2012 Google Inc.
  6. * https://developers.google.com/blockly/
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. /**
  21. * @fileoverview Generating Python for math blocks.
  22. * @author q.neutron@gmail.com (Quynh Neutron)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.Python.math');
  26. goog.require('Blockly.Python');
  27. // If any new block imports any library, add that library name here.
  28. Blockly.Python.addReservedWords('math,random,Number');
  29. Blockly.Python['math_number'] = function(block) {
  30. // Numeric value.
  31. var code = parseFloat(block.getFieldValue('NUM'));
  32. var order;
  33. if (code == Infinity) {
  34. code = 'float("inf")';
  35. order = Blockly.Python.ORDER_FUNCTION_CALL;
  36. } else if (code == -Infinity) {
  37. code = '-float("inf")';
  38. order = Blockly.Python.ORDER_UNARY_SIGN;
  39. } else {
  40. order = code < 0 ? Blockly.Python.ORDER_UNARY_SIGN :
  41. Blockly.Python.ORDER_ATOMIC;
  42. }
  43. return [code, order];
  44. };
  45. Blockly.Python['math_arithmetic'] = function(block) {
  46. // Basic arithmetic operators, and power.
  47. var OPERATORS = {
  48. 'ADD': [' + ', Blockly.Python.ORDER_ADDITIVE],
  49. 'MINUS': [' - ', Blockly.Python.ORDER_ADDITIVE],
  50. 'MULTIPLY': [' * ', Blockly.Python.ORDER_MULTIPLICATIVE],
  51. 'DIVIDE': [' / ', Blockly.Python.ORDER_MULTIPLICATIVE],
  52. 'POWER': [' ** ', Blockly.Python.ORDER_EXPONENTIATION]
  53. };
  54. var tuple = OPERATORS[block.getFieldValue('OP')];
  55. var operator = tuple[0];
  56. var order = tuple[1];
  57. var argument0 = Blockly.Python.valueToCode(block, 'A', order) || '0';
  58. var argument1 = Blockly.Python.valueToCode(block, 'B', order) || '0';
  59. var code = argument0 + operator + argument1;
  60. return [code, order];
  61. // In case of 'DIVIDE', division between integers returns different results
  62. // in Python 2 and 3. However, is not an issue since Blockly does not
  63. // guarantee identical results in all languages. To do otherwise would
  64. // require every operator to be wrapped in a function call. This would kill
  65. // legibility of the generated code.
  66. };
  67. Blockly.Python['math_single'] = function(block) {
  68. // Math operators with single operand.
  69. var operator = block.getFieldValue('OP');
  70. var code;
  71. var arg;
  72. if (operator == 'NEG') {
  73. // Negation is a special case given its different operator precedence.
  74. var code = Blockly.Python.valueToCode(block, 'NUM',
  75. Blockly.Python.ORDER_UNARY_SIGN) || '0';
  76. return ['-' + code, Blockly.Python.ORDER_UNARY_SIGN];
  77. }
  78. Blockly.Python.definitions_['import_math'] = 'import math';
  79. if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') {
  80. arg = Blockly.Python.valueToCode(block, 'NUM',
  81. Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
  82. } else {
  83. arg = Blockly.Python.valueToCode(block, 'NUM',
  84. Blockly.Python.ORDER_NONE) || '0';
  85. }
  86. // First, handle cases which generate values that don't need parentheses
  87. // wrapping the code.
  88. switch (operator) {
  89. case 'ABS':
  90. code = 'math.fabs(' + arg + ')';
  91. break;
  92. case 'ROOT':
  93. code = 'math.sqrt(' + arg + ')';
  94. break;
  95. case 'LN':
  96. code = 'math.log(' + arg + ')';
  97. break;
  98. case 'LOG10':
  99. code = 'math.log10(' + arg + ')';
  100. break;
  101. case 'EXP':
  102. code = 'math.exp(' + arg + ')';
  103. break;
  104. case 'POW10':
  105. code = 'math.pow(10,' + arg + ')';
  106. break;
  107. case 'ROUND':
  108. code = 'round(' + arg + ')';
  109. break;
  110. case 'ROUNDUP':
  111. code = 'math.ceil(' + arg + ')';
  112. break;
  113. case 'ROUNDDOWN':
  114. code = 'math.floor(' + arg + ')';
  115. break;
  116. case 'SIN':
  117. code = 'math.sin(' + arg + ' / 180.0 * math.pi)';
  118. break;
  119. case 'COS':
  120. code = 'math.cos(' + arg + ' / 180.0 * math.pi)';
  121. break;
  122. case 'TAN':
  123. code = 'math.tan(' + arg + ' / 180.0 * math.pi)';
  124. break;
  125. }
  126. if (code) {
  127. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  128. }
  129. // Second, handle cases which generate values that may need parentheses
  130. // wrapping the code.
  131. switch (operator) {
  132. case 'ASIN':
  133. code = 'math.asin(' + arg + ') / math.pi * 180';
  134. break;
  135. case 'ACOS':
  136. code = 'math.acos(' + arg + ') / math.pi * 180';
  137. break;
  138. case 'ATAN':
  139. code = 'math.atan(' + arg + ') / math.pi * 180';
  140. break;
  141. default:
  142. throw 'Unknown math operator: ' + operator;
  143. }
  144. return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
  145. };
  146. Blockly.Python['math_constant'] = function(block) {
  147. // Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
  148. var CONSTANTS = {
  149. 'PI': ['math.pi', Blockly.Python.ORDER_MEMBER],
  150. 'E': ['math.e', Blockly.Python.ORDER_MEMBER],
  151. 'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2',
  152. Blockly.Python.ORDER_MULTIPLICATIVE],
  153. 'SQRT2': ['math.sqrt(2)', Blockly.Python.ORDER_MEMBER],
  154. 'SQRT1_2': ['math.sqrt(1.0 / 2)', Blockly.Python.ORDER_MEMBER],
  155. 'INFINITY': ['float(\'inf\')', Blockly.Python.ORDER_ATOMIC]
  156. };
  157. var constant = block.getFieldValue('CONSTANT');
  158. if (constant != 'INFINITY') {
  159. Blockly.Python.definitions_['import_math'] = 'import math';
  160. }
  161. return CONSTANTS[constant];
  162. };
  163. Blockly.Python['math_number_property'] = function(block) {
  164. // Check if a number is even, odd, prime, whole, positive, or negative
  165. // or if it is divisible by certain number. Returns true or false.
  166. var number_to_check = Blockly.Python.valueToCode(block, 'NUMBER_TO_CHECK',
  167. Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
  168. var dropdown_property = block.getFieldValue('PROPERTY');
  169. var code;
  170. if (dropdown_property == 'PRIME') {
  171. Blockly.Python.definitions_['import_math'] = 'import math';
  172. Blockly.Python.definitions_['from_numbers_import_Number'] =
  173. 'from numbers import Number';
  174. var functionName = Blockly.Python.provideFunction_(
  175. 'math_isPrime',
  176. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(n):',
  177. ' # https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
  178. ' # If n is not a number but a string, try parsing it.',
  179. ' if not isinstance(n, Number):',
  180. ' try:',
  181. ' n = float(n)',
  182. ' except:',
  183. ' return False',
  184. ' if n == 2 or n == 3:',
  185. ' return True',
  186. ' # False if n is negative, is 1, or not whole,' +
  187. ' or if n is divisible by 2 or 3.',
  188. ' if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0:',
  189. ' return False',
  190. ' # Check all the numbers of form 6k +/- 1, up to sqrt(n).',
  191. ' for x in range(6, int(math.sqrt(n)) + 2, 6):',
  192. ' if n % (x - 1) == 0 or n % (x + 1) == 0:',
  193. ' return False',
  194. ' return True']);
  195. code = functionName + '(' + number_to_check + ')';
  196. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  197. }
  198. switch (dropdown_property) {
  199. case 'EVEN':
  200. code = number_to_check + ' % 2 == 0';
  201. break;
  202. case 'ODD':
  203. code = number_to_check + ' % 2 == 1';
  204. break;
  205. case 'WHOLE':
  206. code = number_to_check + ' % 1 == 0';
  207. break;
  208. case 'POSITIVE':
  209. code = number_to_check + ' > 0';
  210. break;
  211. case 'NEGATIVE':
  212. code = number_to_check + ' < 0';
  213. break;
  214. case 'DIVISIBLE_BY':
  215. var divisor = Blockly.Python.valueToCode(block, 'DIVISOR',
  216. Blockly.Python.ORDER_MULTIPLICATIVE);
  217. // If 'divisor' is some code that evals to 0, Python will raise an error.
  218. if (!divisor || divisor == '0') {
  219. return ['False', Blockly.Python.ORDER_ATOMIC];
  220. }
  221. code = number_to_check + ' % ' + divisor + ' == 0';
  222. break;
  223. }
  224. return [code, Blockly.Python.ORDER_RELATIONAL];
  225. };
  226. Blockly.Python['math_change'] = function(block) {
  227. // Add to a variable in place.
  228. Blockly.Python.definitions_['from_numbers_import_Number'] =
  229. 'from numbers import Number';
  230. var argument0 = Blockly.Python.valueToCode(block, 'DELTA',
  231. Blockly.Python.ORDER_ADDITIVE) || '0';
  232. var varName = Blockly.Python.variableDB_.getName(block.getFieldValue('VAR'),
  233. Blockly.Variables.NAME_TYPE);
  234. return varName + ' = (' + varName + ' if isinstance(' + varName +
  235. ', Number) else 0) + ' + argument0 + '\n';
  236. };
  237. // Rounding functions have a single operand.
  238. Blockly.Python['math_round'] = Blockly.Python['math_single'];
  239. // Trigonometry functions have a single operand.
  240. Blockly.Python['math_trig'] = Blockly.Python['math_single'];
  241. Blockly.Python['math_on_list'] = function(block) {
  242. // Math functions for lists.
  243. var func = block.getFieldValue('OP');
  244. var list = Blockly.Python.valueToCode(block, 'LIST',
  245. Blockly.Python.ORDER_NONE) || '[]';
  246. var code;
  247. switch (func) {
  248. case 'SUM':
  249. code = 'sum(' + list + ')';
  250. break;
  251. case 'MIN':
  252. code = 'min(' + list + ')';
  253. break;
  254. case 'MAX':
  255. code = 'max(' + list + ')';
  256. break;
  257. case 'AVERAGE':
  258. Blockly.Python.definitions_['from_numbers_import_Number'] =
  259. 'from numbers import Number';
  260. var functionName = Blockly.Python.provideFunction_(
  261. 'math_mean',
  262. // This operation excludes null and values that aren't int or float:',
  263. // math_mean([null, null, "aString", 1, 9]) == 5.0.',
  264. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
  265. ' localList = [e for e in myList if isinstance(e, Number)]',
  266. ' if not localList: return',
  267. ' return float(sum(localList)) / len(localList)']);
  268. code = functionName + '(' + list + ')';
  269. break;
  270. case 'MEDIAN':
  271. Blockly.Python.definitions_['from_numbers_import_Number'] =
  272. 'from numbers import Number';
  273. var functionName = Blockly.Python.provideFunction_(
  274. 'math_median',
  275. // This operation excludes null values:
  276. // math_median([null, null, 1, 3]) == 2.0.
  277. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
  278. ' localList = sorted([e for e in myList if isinstance(e, Number)])',
  279. ' if not localList: return',
  280. ' if len(localList) % 2 == 0:',
  281. ' return (localList[len(localList) // 2 - 1] + ' +
  282. 'localList[len(localList) // 2]) / 2.0',
  283. ' else:',
  284. ' return localList[(len(localList) - 1) // 2]']);
  285. code = functionName + '(' + list + ')';
  286. break;
  287. case 'MODE':
  288. var functionName = Blockly.Python.provideFunction_(
  289. 'math_modes',
  290. // As a list of numbers can contain more than one mode,
  291. // the returned result is provided as an array.
  292. // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1].
  293. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(some_list):',
  294. ' modes = []',
  295. ' # Using a lists of [item, count] to keep count rather than dict',
  296. ' # to avoid "unhashable" errors when the counted item is ' +
  297. 'itself a list or dict.',
  298. ' counts = []',
  299. ' maxCount = 1',
  300. ' for item in some_list:',
  301. ' found = False',
  302. ' for count in counts:',
  303. ' if count[0] == item:',
  304. ' count[1] += 1',
  305. ' maxCount = max(maxCount, count[1])',
  306. ' found = True',
  307. ' if not found:',
  308. ' counts.append([item, 1])',
  309. ' for counted_item, item_count in counts:',
  310. ' if item_count == maxCount:',
  311. ' modes.append(counted_item)',
  312. ' return modes']);
  313. code = functionName + '(' + list + ')';
  314. break;
  315. case 'STD_DEV':
  316. Blockly.Python.definitions_['import_math'] = 'import math';
  317. var functionName = Blockly.Python.provideFunction_(
  318. 'math_standard_deviation',
  319. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(numbers):',
  320. ' n = len(numbers)',
  321. ' if n == 0: return',
  322. ' mean = float(sum(numbers)) / n',
  323. ' variance = sum((x - mean) ** 2 for x in numbers) / n',
  324. ' return math.sqrt(variance)']);
  325. code = functionName + '(' + list + ')';
  326. break;
  327. case 'RANDOM':
  328. Blockly.Python.definitions_['import_random'] = 'import random';
  329. code = 'random.choice(' + list + ')';
  330. break;
  331. default:
  332. throw 'Unknown operator: ' + func;
  333. }
  334. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  335. };
  336. Blockly.Python['math_modulo'] = function(block) {
  337. // Remainder computation.
  338. var argument0 = Blockly.Python.valueToCode(block, 'DIVIDEND',
  339. Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
  340. var argument1 = Blockly.Python.valueToCode(block, 'DIVISOR',
  341. Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
  342. var code = argument0 + ' % ' + argument1;
  343. return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
  344. };
  345. Blockly.Python['math_constrain'] = function(block) {
  346. // Constrain a number between two limits.
  347. var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
  348. Blockly.Python.ORDER_NONE) || '0';
  349. var argument1 = Blockly.Python.valueToCode(block, 'LOW',
  350. Blockly.Python.ORDER_NONE) || '0';
  351. var argument2 = Blockly.Python.valueToCode(block, 'HIGH',
  352. Blockly.Python.ORDER_NONE) || 'float(\'inf\')';
  353. var code = 'min(max(' + argument0 + ', ' + argument1 + '), ' +
  354. argument2 + ')';
  355. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  356. };
  357. Blockly.Python['math_random_int'] = function(block) {
  358. // Random integer between [X] and [Y].
  359. Blockly.Python.definitions_['import_random'] = 'import random';
  360. var argument0 = Blockly.Python.valueToCode(block, 'FROM',
  361. Blockly.Python.ORDER_NONE) || '0';
  362. var argument1 = Blockly.Python.valueToCode(block, 'TO',
  363. Blockly.Python.ORDER_NONE) || '0';
  364. var code = 'random.randint(' + argument0 + ', ' + argument1 + ')';
  365. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  366. };
  367. Blockly.Python['math_random_float'] = function(block) {
  368. // Random fraction between 0 and 1.
  369. Blockly.Python.definitions_['import_random'] = 'import random';
  370. return ['random.random()', Blockly.Python.ORDER_FUNCTION_CALL];
  371. };