| | import random |
| | import json |
| | import operator |
| |
|
| | |
| | num_samples = 500000 |
| | |
| | min_value = -99.99 |
| | max_value = 99.99 |
| | |
| | operations = { |
| | '+': operator.add, |
| | '-': operator.sub, |
| | '*': operator.mul, |
| | '/': operator.truediv |
| | } |
| |
|
| | 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 |
| |
|
| | |
| | data = [] |
| | for _ in range(num_samples): |
| | num1 = generate_random_number() |
| | num2 = generate_random_number() |
| | num3 = generate_random_number() |
| | |
| | if num2 == 0.0: |
| | num2 = generate_random_number() |
| | if num3 == 0.0: |
| | num3 = generate_random_number() |
| |
|
| | |
| | operation1 = random.choice(list(operations.keys())) |
| | operation2 = random.choice(list(operations.keys())) |
| | |
| | |
| | if random.choice([True, False]): |
| | |
| | expression = f"({num1} {operation1} {num2}) {operation2} {num3}" |
| | if operation1 == '/': |
| | intermediate_result = safe_division(num1, num2) |
| | else: |
| | intermediate_result = operations[operation1](num1, num2) |
| | if operation2 == '/' and intermediate_result != 0: |
| | result = safe_division(intermediate_result, num3) |
| | else: |
| | result = operations[operation2](intermediate_result, num3) |
| | else: |
| | |
| | expression = f"{num1} {operation1} {num2} {operation2} {num3}" |
| | if operation1 == '/': |
| | intermediate_result = safe_division(num1, num2) |
| | else: |
| | intermediate_result = operations[operation1](num1, num2) |
| | if operation2 == '/': |
| | result = safe_division(intermediate_result, num3) |
| | else: |
| | result = operations[operation2](intermediate_result, num3) |
| |
|
| | output = "%.4f" % result |
| | data.append({'instruction': expression, 'output': output}) |
| |
|
| | |
| | out_file = 'arithmetic-float-complex.json' |
| | with open(out_file, 'w') as f: |
| | json.dump(data, f) |