如果某个值等于yx^2,当x和y都是整数时,如何在python中找到x和y的值

问题描述 投票:0回答:1
import sympy

def find_integer_values(value):
  x, y = sympy.symbols('x y', integer=True)
  equation = sympy.Eq(y * x**2, value)         

  # Solve for integer values of x and y
  solutions = sympy.solve(equation, (x, y), dict=True)

  # Filter solutions to include only integers
  integer_solutions = [(sol[x], sol[y]) for sol in solutions if sympy.simplify(sol[x]).is_integer and sympy.simplify(sol[y]).is_integer]
 
  return integer_solutions

# Example usage:
given_value = 1920

integer_solutions = find_integer_values(given_value)

if integer_solutions:
  print("Integer solutions for x and y:", integer_solutions)
else:
  print("No integer solutions found.")

代码应该找到 x 和 y 的值,它们都是整数。但这部分代码有问题——

integer_solutions = [(sol[x], sol[y]) for sol in solutions if sympy.simplify(sol[x]).is_integer and sympy.simplify(sol[y]).is_integer]

非常感谢任何有关如何解决此问题的建议。

python sympy
1个回答
0
投票

代码中的问题在于如何检查 x 和 y 的解是否为整数。使用

sympy.simplify(sol[x]).is_integer
sympy.simplify(sol[y]).is_integer
并不总是能提供准确的结果,尤其是在处理符号表达式时。

相反,您可以使用

sympy.Integer(sol[x])
sympy.Integer(sol[y])
直接检查解是否为整数。

import sympy

def find_integer_values(value):
    x, y = sympy.symbols('x y', integer=True)
    equation = sympy.Eq(y * x**2, value)

    # Solve for integer values ​​of x and y
    solutions = sympy.solve(equation, (x, y), dict=True)

    # Filter solutions to include only integers
    integer_solutions = [(sol[x], sol[y]) for sol in solutions if sympy.Integer(sol[x]) and sympy.Integer(sol[y])]

    return integer_solutions

# Example of use:
given_value = 1920

integer_solutions = find_integer_values(given_value)

if integer_solutions:
    print("Integer solutions for x and y:", integer_solutions)
else:
    print("No integer solution found.")

此修改应该能够准确过滤掉非整数解,并为 x 和 y 提供正确的整数解。

© www.soinside.com 2019 - 2024. All rights reserved.