import random import json import operator import math # Define the number of samples you want to generate num_samples = 500000 # Define the range for the random numbers min_value = -99.99 max_value = 99.99 # Define the arithmetic operations and their corresponding functions operations = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, '^': operator.pow } def generate_random_number(): return float("%.3f" % random.uniform(min_value, max_value)) def safe_division(numerator, denominator): return numerator if denominator == 0 else numerator / denominator def safe_power(base, exponent): try: return math.pow(base, exponent) except OverflowError: return float('inf') if base > 0 else float('-inf') # Function to evaluate expressions safely def evaluate_expression(expression): try: return eval(expression, {"__builtins__": {}}, operations) except ZeroDivisionError: return None # Function to generate a random arithmetic expression def generate_expression(depth=0): num1 = generate_random_number() num2 = generate_random_number() operation = random.choice(list(operations.keys())) if operation == '/': # Ensure second number is not zero for division num2 = num2 or generate_random_number() if operation == '^': # Validate power operations num1, num2 = min(num1, 10), min(num2, 10) # Limit the values for power operations to prevent overflow expression = f"{num1} {operation} {num2}" # Add a chance to nest expressions inside parentheses if depth < 2 and random.choice([True, False]): # Limit the depth to prevent overly complex expressions nested_expression = generate_expression(depth + 1) if random.choice([True, False]): expression = f"({expression}) {operation} ({nested_expression})" else: expression = f"({expression}) {operation} {nested_expression}" return expression # Generate complex data including unary operations and nested expressions data = [] while len(data) < num_samples: expression = generate_expression() result = evaluate_expression(expression) if result is not None: # Only accept expressions that don't lead to division by zero output = "%.4f" % result data.append({'instruction': expression, 'output': output}) # Create the dataset out_file = 'arithmetic-float-complex.json' with open(out_file, 'w') as f: json.dump(data, f, indent=2) print(f"Generated {len(data)} samples.")