math.js 14 KB

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