Why using math.sin() and got a wrong result? (SOLVED)

Hi guys
I am learning defold engine serval days ago, and today i met a problem that
the math.sin() function output a wrong result.

the code is

function update(self, dt)
	-- Add update code here
	-- Remove this function if not needed
		self.position = go.get_position()
		self.x= self.position.x
		self.y= self.position.y
		self.t = self.t + dt 
		--self.dx = math.cos(self.t * self.speed) * self.radius 
		--self.dy = math.sin(self.t * self.speed) * self.radius
		self.dx = math.cos(self.radius) *self.t *self.speed
		self.dy = math.sin(self.radius) *self.t *self.speed
		self.pos = vmath.vector3() 
		print(dt)
		print(math.cos(self.radius))
		print(math.sin(self.radius))
		print(self.dx)
		print(self.dy)
		self.pos.x = self.x + self.dx 
    	self.pos.y = self.y + self.dy
    	go.set_position(self.pos) 
    	
	
end

but the result was a different at the angle 30.86Ā°
sin(30.86 Ā°) should be ā‰ˆ 0.5129 but the output was a negative value

DEBUG:SCRIPT: vmath.quat(0, 0, 0, 1)
INFO:DLIB: SSDP: Started on address 192.168.31.161
DEBUG:SCRIPT: 30.867730175872
DEBUG:SCRIPT: 0.016666667535901
DEBUG:SCRIPT: 0.85346587444752
DEBUG:SCRIPT: -0.52114873227662

so i came here to look for help, is it any wrong with my code? thanks!

Normally, you donā€™t put radius value into sin() or cos(). Usually the equation for a radial positioning of something looks like this:

local angle = math.pi
local x = math.cos(angle) * radius
local y = math.sin(angle) * radius

Angle should be in radians.

1 Like

thanks sergey

actually the radius variable is the angle
i did not change the variable name

Maybe clear up the code and console output before posting as there is several weird things that I dont understand.
First thing you print is deltatime (dt) and that is certainly not first in the output (neither the quat or 30.86ā€¦)
Then you show is a line of math.cos with self.radius but nowhere in the code is self.radius set or altered which really confuses me. How am I supposed to read the output to begin with? Where do you print the angle?
Try print(self.radius) and print(math.sin(self.radius))

thanks

finally i found where my error from

i have to transform the angle to radius
so my code should be
math.cos(math.rad(self.radius))

and the result was correct

1 Like

Good that you got it working. All math.* functions expect angles expressed in radians. The same goes for the vmath.* functions.

I think there might be a slight error in naming here which can be confusing for some readers.

If the ā€œradiusā€ is an angle, I think itā€™s better to name it so (e.g. ā€œself.angleā€) since radius is the distance from the center of a circle to itā€™s edge (i.e. not an angle)

What might cause this confusion is the name radians, which is a unit of measurement of angles. (Note that your fix suggests that your angle was measured in degrees).

5 Likes