我正在尝试将库仑定律公式实现到 Java 中,但没有库仑常数,在非现实场景中显示粒子运动时基本上不需要库仑常数。问题是,我被困在如何编写对我的粒子施加力的方法上,这样当电荷均为正或均为负时,粒子排斥,当它们不同时它们吸引。到目前为止,我已经写了一种计算力的方法,但它似乎不能正常工作,我现在已经没有想法了。
这是我的代码的一个最小示例:
import java.util.ArrayList;
import java.util.List;
public class ChargedParticlesSimulation {
public static void main(String[] args) {
List<ChargedParticle> chargedParticles = generateChargedParticles(5);
applyCoulombsLaw(chargedParticles);
}
private static List<ChargedParticle> generateChargedParticles(int numParticles) {
List<ChargedParticle> chargedParticles = new ArrayList<>();
for (int i = 0; i < numParticles; i++) {
double x = Math.random() * 100;
double y = Math.random() * 100;
double charge = (Math.random() < 0.5) ? 500000 : -500000;
chargedParticles.add(new ChargedParticle(x, y, charge));
}
return chargedParticles;
}
private static void applyCoulombsLaw(List<ChargedParticle> chargedParticles) {
for (int i = 0; i < chargedParticles.size(); i++) {
ChargedParticle particle1 = chargedParticles.get(i);
for (int j = i + 1; j < chargedParticles.size(); j++) {
ChargedParticle particle2 = chargedParticles.get(j);
double deltaX = particle2.xPos - particle1.xPos;
double deltaY = particle2.yPos - particle1.yPos;
double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
double force = Math.abs(particle1.charge * particle2.charge) / (distance * distance);
double forceX = force * deltaX / distance;
double forceY = force * deltaY / distance;
}
}
}
}
class ChargedParticle {
double xPos;
double yPos;
double charge;
ChargedParticle(double x, double y, double charge) {
this.xPos = x;
this.yPos = y;
this.charge = charge;
}
}
这是我尝试过但不起作用的方法:
private void applyCoulombsLaw(List<ChargedParticle> chargedParticles) {
for (int i = 0; i < chargedParticles.size(); i++) {
ChargedParticle particle1 = chargedParticles.get(i);
for (int j = i + 1; j < chargedParticles.size(); j++) {
ChargedParticle particle2 = chargedParticles.get(j);
double deltaX = particle2.xPos - particle1.xPos;
double deltaY = particle2.yPos - particle1.yPos;
double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
double force;
force = Math.abs(particle1.charge * particle2.charge) / (distance * distance);
double forceX = force * deltaX / distance;
double forceY = force * deltaY / distance;
particle1.xVelocity += forceX / particle1.charge * 0.010;
particle1.yVelocity += forceY / particle1.charge * 0.010;
particle2.xVelocity -= forceX / particle2.charge * 0.010;
particle2.yVelocity -= forceY / particle2.charge * 0.010;
}
}
}
对此的任何提示或解决方案都会对我有很大帮助。谢谢。