math.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. 'MODULO': [' % ', Blockly.Python.ORDER_MULTIPLICATIVE]
  54. };
  55. var tuple = OPERATORS[block.getFieldValue('OP')];
  56. var operator = tuple[0];
  57. var order = tuple[1];
  58. var argument0 = Blockly.Python.valueToCode(block, 'A', order) || '___';
  59. var argument1 = Blockly.Python.valueToCode(block, 'B', order) || '___';
  60. var code = argument0 + operator + argument1;
  61. return [code, order];
  62. // In case of 'DIVIDE', division between integers returns different results
  63. // in Python 2 and 3. However, is not an issue since Blockly does not
  64. // guarantee identical results in all languages. To do otherwise would
  65. // require every operator to be wrapped in a function call. This would kill
  66. // legibility of the generated code.
  67. };
  68. Blockly.Python['math_single'] = function(block) {
  69. // Math operators with single operand.
  70. var operator = block.getFieldValue('OP');
  71. var code;
  72. var arg;
  73. if (operator == 'NEG') {
  74. // Negation is a special case given its different operator precedence.
  75. var code = Blockly.Python.valueToCode(block, 'NUM',
  76. Blockly.Python.ORDER_UNARY_SIGN) || '___';
  77. return ['-' + code, Blockly.Python.ORDER_UNARY_SIGN];
  78. }
  79. if (operator != 'ABS' && operator != 'POW' && operator != 'ROUND') {
  80. Blockly.Python.definitions_['import_math'] = 'import math';
  81. }
  82. if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') {
  83. arg = Blockly.Python.valueToCode(block, 'NUM',
  84. Blockly.Python.ORDER_MULTIPLICATIVE) || '___';
  85. } else {
  86. arg = Blockly.Python.valueToCode(block, 'NUM',
  87. Blockly.Python.ORDER_NONE) || '___';
  88. }
  89. // First, handle cases which generate values that don't need parentheses
  90. // wrapping the code.
  91. switch (operator) {
  92. case 'ABS':
  93. code = 'abs(' + arg + ')';
  94. break;
  95. case 'ROOT':
  96. code = 'math.sqrt(' + arg + ')';
  97. break;
  98. case 'DEGRAD_DEG':
  99. code = 'math.degrees(' + arg + ')';
  100. break;
  101. case 'DEGRAD_RAD':
  102. code = 'math.radians(' + arg + ')';
  103. break;
  104. case 'LN':
  105. code = 'math.log(' + arg + ')';
  106. break;
  107. case 'LOG10':
  108. code = 'math.log10(' + arg + ')';
  109. break;
  110. case 'EXP':
  111. code = 'math.exp(' + arg + ')';
  112. break;
  113. case 'POW10':
  114. code = 'pow(10,' + arg + ')';
  115. break;
  116. case 'ROUND':
  117. code = 'round(' + arg + ')';
  118. break;
  119. case 'ROUNDUP':
  120. code = 'math.ceil(' + arg + ')';
  121. break;
  122. case 'ROUNDDOWN':
  123. code = 'math.floor(' + arg + ')';
  124. break;
  125. case 'SIN':
  126. code = 'math.sin(' + arg + ' / 180.0 * math.pi)';
  127. break;
  128. case 'COS':
  129. code = 'math.cos(' + arg + ' / 180.0 * math.pi)';
  130. break;
  131. case 'TAN':
  132. code = 'math.tan(' + arg + ' / 180.0 * math.pi)';
  133. break;
  134. }
  135. if (code) {
  136. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  137. }
  138. // Second, handle cases which generate values that may need parentheses
  139. // wrapping the code.
  140. switch (operator) {
  141. case 'ASIN':
  142. // code = 'math.asin(' + arg + ') / math.pi * 180';
  143. code = 'math.asin(' + arg + ')';
  144. break;
  145. case 'ACOS':
  146. // code = 'math.acos(' + arg + ') / math.pi * 180';
  147. code = 'math.acos(' + arg + ')';
  148. break;
  149. case 'ATAN':
  150. // code = 'math.atan(' + arg + ') / math.pi * 180';
  151. code = 'math.atan(' + arg + ')';
  152. break;
  153. default:
  154. throw 'Unknown math operator: ' + operator;
  155. }
  156. return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
  157. };
  158. Blockly.Python['math_constant'] = function(block) {
  159. // Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
  160. var CONSTANTS = {
  161. 'PI': ['math.pi', Blockly.Python.ORDER_MEMBER],
  162. 'E': ['math.e', Blockly.Python.ORDER_MEMBER],
  163. 'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2',
  164. Blockly.Python.ORDER_MULTIPLICATIVE],
  165. 'SQRT2': ['math.sqrt(2)', Blockly.Python.ORDER_MEMBER],
  166. 'SQRT1_2': ['math.sqrt(1.0 / 2)', Blockly.Python.ORDER_MEMBER],
  167. 'INFINITY': ['float(\'inf\')', Blockly.Python.ORDER_ATOMIC]
  168. };
  169. var constant = block.getFieldValue('CONSTANT');
  170. if (constant != 'INFINITY') {
  171. Blockly.Python.definitions_['import_math'] = 'import math';
  172. }
  173. return CONSTANTS[constant];
  174. };
  175. Blockly.Python['math_number_property'] = function(block) {
  176. // Check if a number is even, odd, prime, whole, positive, or negative
  177. // or if it is divisible by certain number. Returns true or false.
  178. var number_to_check = Blockly.Python.valueToCode(block, 'NUMBER_TO_CHECK',
  179. Blockly.Python.ORDER_MULTIPLICATIVE) || '___';
  180. var dropdown_property = block.getFieldValue('PROPERTY');
  181. var code;
  182. if (dropdown_property == 'PRIME') {
  183. Blockly.Python.definitions_['import_math'] = 'import math';
  184. Blockly.Python.definitions_['from_numbers_import_Number'] =
  185. 'from numbers import Number';
  186. var functionName = Blockly.Python.provideFunction_(
  187. 'math_isPrime',
  188. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(n):',
  189. ' # https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
  190. ' # If n is not a number but a string, try parsing it.',
  191. ' if not isinstance(n, Number):',
  192. ' try:',
  193. ' n = float(n)',
  194. ' except:',
  195. ' return False',
  196. ' if n == 2 or n == 3:',
  197. ' return True',
  198. ' # False if n is negative, is 1, or not whole,' +
  199. ' or if n is divisible by 2 or 3.',
  200. ' if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0:',
  201. ' return False',
  202. ' # Check all the numbers of form 6k +/- 1, up to sqrt(n).',
  203. ' for x in range(6, int(math.sqrt(n)) + 2, 6):',
  204. ' if n % (x - 1) == 0 or n % (x + 1) == 0:',
  205. ' return False',
  206. ' return True']);
  207. code = functionName + '(' + number_to_check + ')';
  208. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  209. }
  210. switch (dropdown_property) {
  211. case 'EVEN':
  212. code = number_to_check + ' % 2 == 0';
  213. break;
  214. case 'ODD':
  215. code = number_to_check + ' % 2 == 1';
  216. break;
  217. case 'WHOLE':
  218. code = number_to_check + ' % 1 == 0';
  219. break;
  220. case 'POSITIVE':
  221. code = number_to_check + ' > 0';
  222. break;
  223. case 'NEGATIVE':
  224. code = number_to_check + ' < 0';
  225. break;
  226. case 'DIVISIBLE_BY':
  227. var divisor = Blockly.Python.valueToCode(block, 'DIVISOR',
  228. Blockly.Python.ORDER_MULTIPLICATIVE);
  229. // If 'divisor' is some code that evals to 0, Python will raise an error.
  230. if (!divisor || divisor == '0') {
  231. return ['False', Blockly.Python.ORDER_ATOMIC];
  232. }
  233. code = number_to_check + ' % ' + divisor + ' == 0';
  234. break;
  235. }
  236. return [code, Blockly.Python.ORDER_RELATIONAL];
  237. };
  238. Blockly.Python['math_change'] = function(block) {
  239. // Add to a variable in place.
  240. //Blockly.Python.definitions_['from_numbers_import_Number'] =
  241. // 'from numbers import Number';
  242. var argument0 = Blockly.Python.valueToCode(block, 'DELTA',
  243. Blockly.Python.ORDER_ADDITIVE) || '___';
  244. var varName = Blockly.Python.variableDB_.getName(block.getFieldValue('VAR'),
  245. Blockly.Variables.NAME_TYPE);
  246. return varName + ' += ' + argument0 + '\n';
  247. };
  248. // Rounding functions have a single operand.
  249. Blockly.Python['math_round'] = Blockly.Python['math_single'];
  250. // Trigonometry functions have a single operand.
  251. Blockly.Python['math_trig'] = Blockly.Python['math_single'];
  252. Blockly.Python['math_on_list'] = function(block) {
  253. // Math functions for lists.
  254. var func = block.getFieldValue('OP');
  255. var list = Blockly.Python.valueToCode(block, 'LIST',
  256. Blockly.Python.ORDER_NONE) || '___';
  257. var code;
  258. switch (func) {
  259. case 'SUM':
  260. code = 'sum(' + list + ')';
  261. break;
  262. case 'MIN':
  263. code = 'min(' + list + ')';
  264. break;
  265. case 'MAX':
  266. code = 'max(' + list + ')';
  267. break;
  268. case 'AVERAGE':
  269. Blockly.Python.definitions_['from_numbers_import_Number'] =
  270. 'from numbers import Number';
  271. var functionName = Blockly.Python.provideFunction_(
  272. 'math_mean',
  273. // This operation excludes null and values that aren't int or float:',
  274. // math_mean([null, null, "aString", 1, 9]) == 5.0.',
  275. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
  276. ' localList = [e for e in myList if isinstance(e, Number)]',
  277. ' if not localList: return',
  278. ' return float(sum(localList)) / len(localList)']);
  279. code = functionName + '(' + list + ')';
  280. break;
  281. case 'MEDIAN':
  282. Blockly.Python.definitions_['from_numbers_import_Number'] =
  283. 'from numbers import Number';
  284. var functionName = Blockly.Python.provideFunction_(
  285. 'math_median',
  286. // This operation excludes null values:
  287. // math_median([null, null, 1, 3]) == 2.0.
  288. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
  289. ' localList = sorted([e for e in myList if isinstance(e, Number)])',
  290. ' if not localList: return',
  291. ' if len(localList) % 2 == 0:',
  292. ' return (localList[len(localList) // 2 - 1] + ' +
  293. 'localList[len(localList) // 2]) / 2.0',
  294. ' else:',
  295. ' return localList[(len(localList) - 1) // 2]']);
  296. code = functionName + '(' + list + ')';
  297. break;
  298. case 'MODE':
  299. var functionName = Blockly.Python.provideFunction_(
  300. 'math_modes',
  301. // As a list of numbers can contain more than one mode,
  302. // the returned result is provided as an array.
  303. // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1].
  304. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(some_list):',
  305. ' modes = []',
  306. ' # Using a lists of [item, count] to keep count rather than dict',
  307. ' # to avoid "unhashable" errors when the counted item is ' +
  308. 'itself a list or dict.',
  309. ' counts = []',
  310. ' maxCount = 1',
  311. ' for item in some_list:',
  312. ' found = False',
  313. ' for count in counts:',
  314. ' if count[0] == item:',
  315. ' count[1] += 1',
  316. ' maxCount = max(maxCount, count[1])',
  317. ' found = True',
  318. ' if not found:',
  319. ' counts.append([item, 1])',
  320. ' for counted_item, item_count in counts:',
  321. ' if item_count == maxCount:',
  322. ' modes.append(counted_item)',
  323. ' return modes']);
  324. code = functionName + '(' + list + ')';
  325. break;
  326. case 'STD_DEV':
  327. Blockly.Python.definitions_['import_math'] = 'import math';
  328. var functionName = Blockly.Python.provideFunction_(
  329. 'math_standard_deviation',
  330. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(numbers):',
  331. ' n = len(numbers)',
  332. ' if n == 0: return',
  333. ' mean = float(sum(numbers)) / n',
  334. ' variance = sum((x - mean) ** 2 for x in numbers) / n',
  335. ' return math.sqrt(variance)']);
  336. code = functionName + '(' + list + ')';
  337. break;
  338. case 'RANDOM':
  339. Blockly.Python.definitions_['import_random'] = 'import random';
  340. code = 'random.choice(' + list + ')';
  341. break;
  342. default:
  343. throw 'Unknown operator: ' + func;
  344. }
  345. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  346. };
  347. Blockly.Python['math_modulo'] = function(block) {
  348. // Remainder computation.
  349. var argument0 = Blockly.Python.valueToCode(block, 'DIVIDEND',
  350. Blockly.Python.ORDER_MULTIPLICATIVE) || '___';
  351. var argument1 = Blockly.Python.valueToCode(block, 'DIVISOR',
  352. Blockly.Python.ORDER_MULTIPLICATIVE) || '___';
  353. var code = argument0 + ' % ' + argument1;
  354. return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
  355. };
  356. Blockly.Python['math_constrain'] = function(block) {
  357. // Constrain a number between two limits.
  358. var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
  359. Blockly.Python.ORDER_NONE) || '___';
  360. var argument1 = Blockly.Python.valueToCode(block, 'LOW',
  361. Blockly.Python.ORDER_NONE) || '___';
  362. var argument2 = Blockly.Python.valueToCode(block, 'HIGH',
  363. Blockly.Python.ORDER_NONE) || '___';
  364. var code = 'min(max(' + argument0 + ', ' + argument1 + '), ' +
  365. argument2 + ')';
  366. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  367. };
  368. Blockly.Python['math_random_int'] = function(block) {
  369. // Random integer between [X] and [Y].
  370. // Blockly.Python.definitions_.import_time = "import time";
  371. Blockly.Python.definitions_['import_random'] = 'import random';
  372. // Blockly.Python.codeFunctions_.random_seed = "random.seed(time.ticks_cpu())";
  373. var argument0 = Blockly.Python.valueToCode(block, 'FROM',
  374. Blockly.Python.ORDER_NONE) || '___';
  375. var argument1 = Blockly.Python.valueToCode(block, 'TO',
  376. Blockly.Python.ORDER_NONE) || '___';
  377. var code = 'random.randint(' + argument0 + ', ' + argument1 + ')';
  378. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  379. };
  380. Blockly.Python['math_random_float'] = function(block) {
  381. // Random fraction between 0 and 1.
  382. Blockly.Python.definitions_['import_random'] = 'import random';
  383. return ['random.random()', Blockly.Python.ORDER_FUNCTION_CALL];
  384. };
  385. Blockly.Python['math_sum_values'] = function(block) {
  386. var sum1 = Blockly.Python.valueToCode(block,"SUM1",Blockly.Python.ORDER_ATOMIC) || "";
  387. var sum2 = Blockly.Python.valueToCode(block,"SUM2",Blockly.Python.ORDER_ATOMIC) || "";
  388. var code = "sum(" + sum1 + " " + sum2 + ")";
  389. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  390. }
  391. Blockly.Python['math_sum_common'] = function(block) {
  392. var sum1 = Blockly.Python.valueToCode(block,"SUM1",Blockly.Python.ORDER_ATOMIC) || "";
  393. var code = "sum(" + sum1 +")";
  394. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  395. }